我在主窗口中创建了一个按钮,单击该按钮将打开一个搜索窗口,其中包含一个树形小部件,其中包含来自 MySql 数据库的数据行。如果我通过 .py 文件单独打开搜索窗口,它会显示数据,但是当我通过我编程的按钮打开它时,不会显示任何数据。这是运行主窗口并创建按钮功能以打开搜索窗口的程序的代码:
from PyQt4 import QtGui
from MainMenu import Ui_MainWindow
from StudentSearch import Ui_Student_search
import DB_manager_students
class MainWindow(Ui_MainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.pushButton_3.clicked.connect(self.handleButton)
self.window2 = None
def handleButton(self):
if self.window2 is None:
self.window2 = Student_search()
self.window2.show()
class Student_search(Ui_Student_search):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setupUi(self)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
我做错了什么?还有为什么我自己打开它会显示数据,而我这样打开就不会显示数据?
编辑:
来自 Student_search.py
class Ui_Student_search(QtGui.QWidget):
def __init__(self, database, tableName):
QtGui.QWidget.__init__(self)
self.dbu = DB_manager_students.DatabaseUtility(database, tableName)
self.setupUi(self)
self.UpdateTree()
(...)
def UpdateTree(self):
col = self.dbu.GetColumns()
table = self.dbu.GetTable()
for c in range(len(col)):
self.StudentTreeWidget.headerItem().setText(c, col[c][0])
self.StudentTreeWidget.clear()
for item in range(len(table)):
QtGui.QTreeWidgetItem(self.StudentTreeWidget)
for value in range(len(table[item])):
self.StudentTreeWidget.topLevelItem(item).setText(value, str(table[item][value]))
编辑:
最佳答案
这是您的基本小部件类
class Ui_Student_search(QtGui.QWidget):
def __init__(self, database, tableName):
QtGui.QWidget.__init__(self)
self.dbu = DB_manager_students.DatabaseUtility(database, tableName)
self.setupUi(self)
self.UpdateTree()
当您实例化 Ui_Student_search()
时,Ui_Student_search.__init__()
方法将运行,该方法将创建数据库实用程序、创建 GUI 并运行 UpdateTree( )
。
现在,您创建一个新类 - Student_search
- 继承自 Ui_Student_search
类
class Student_search(Ui_Student_search):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setupUi(self)
但是,当实例化此类并运行 Student_search.__init__()
时,它只执行 Ui_Student_search.__init__()
所执行的操作的一半。它不会创建数据库管理器或更新树。
您应该做的是调用父类 __init__
方法,以便 Ui_Student_search.__init__()
可以运行并执行所有这些操作。另请注意,您需要将 database
和 tablename
参数传递给 Ui_Student_search.__init__
方法。
class Student_search(Ui_Student_search):
def __init__(self, database, tablename, parent=None):
Ui_Student_search.__init__(self, parent, database, tablename)
Python 有更简单的语法来调用基父类上的方法。
class Student_search(Ui_Student_search):
def __init__(self, database, tablename, parent=None):
super(Student_search, self).__init__(parent, database, tablename)
这也意味着您需要更新 MainWindow
以向 Student_search
提供必要的构造函数参数
def handleButton(self):
if self.window2 is None:
database = '???'
tablename = 'xxx'
self.window2 = Student_search(database, tablename, parent=self)
self.window2.show()
关于python - 数据未显示在 pyqt UI 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36603530/