我是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
类重命名为MainWindow
。MainWindow
只需要从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_())