Qt Designer和Python在单独的functions.py中运行一个函数



我是python新手。我在QtDesigner中设计了一个GUI,并将代码翻译为与python一起使用。因为如果我在GUI中更改某些内容,它将覆盖我的代码,所以我想为函数使用单独的文件。

代码应该在主窗口显示后运行,但我得到一个错误

Ui_MainWindow' object没有属性'fillContactList'

如果有人能帮助我,我会非常感激。

import sys
import psycopg2
from PySide6 import (QtCore, QtWidgets, QtGui)
from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale,
QMetaObject, QObject, QPoint, QRect,
QSize, QTime, QUrl, Qt)
from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor,
QFont, QFontDatabase, QGradient, QIcon,
QImage, QKeySequence, QLinearGradient, QPainter,
QPalette, QPixmap, QRadialGradient, QTransform)
from PySide6.QtWidgets import (QApplication, QLabel, QMainWindow, QMenuBar,
QSizePolicy, QStatusBar, QTabWidget, QWidget)
from mainwindow import Ui_MainWindow
class mainwindow(QMainWindow, Ui_MainWindow):
def __init__(self):
super(mainwindow, self).__init__()
self.setWindowTitle("Skills In Motion")
def fillContactList(self):
conn = psycopg2.connect(database="CRM", user="********", password="*****", host="localhost", port=5432)
cur = conn.cursor()
dataset = cur.execute("SELECT cust_name, cust_pk FROM customer")
results = cur.fetchall()

rowPosition = 0
for customers in results:
self.contactsTable.insertRow(rowPosition)
self.contactsTable.setItem(rowPosition,0,QtWidgets.QTableWidgetItem(customers[0]))
self.contactsTable.setItem(rowPosition,1,QtWidgets.QTableWidgetItem(str(customers[1])))
self.contactsTable.hideColumn(1)
rowPosition = rowPosition+1
self.contactsTable.itemSelectionChanged.connect(self.onSelectionContact)
self.contactsTable.selectRow(0)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
ui.fillContactList()
MainWindow.show()
sys.exit(app.exec())```

首先,将mainwindow类重命名为MainWindowMainWindow只需要从QMainWindow子类化。

创建Ui_MainWindow对象后,使用它的setupUi方法来构建MainWindow对象。您在设计器中创建的所有小部件引用都可以作为Ui_MainWindow对象的属性使用。

因此,将其存储在主窗口作为self.ui = Ui_MainWindow()。构建主窗口作为self.ui.setupUi(self)。引用任何小部件,如self.ui.contactsTable

您需要创建MainWindow类的对象,而不是QMainWindow

试试:

import sys
from PySide6.QtWidgets import QMainWindow, QApplication
from mainwindow import Ui_MainWindow

class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Skills In Motion")
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.fillContactList()
def fillContactList(self):
# Reference Table like this
# self.ui.contactsTable
pass

if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())

相关内容

  • 没有找到相关文章

最新更新