我写了一个可执行程序。我的想法是在运行时加载QTreeWidget中的所有数据项。这就是我想使用QThread的原因。我不希望GUI在处理大数据时冻结。但是当我运行这个示例程序时,无论如何都会冻结。但为什么呢?
import sys
from PyQt4.QtCore import QThread, pyqtSignal, Qt
from PyQt4.QtGui import QVBoxLayout, QPushButton, QDialog, QProgressBar, QApplication, \
QMessageBox, QTreeWidget, QTreeWidgetItem
class Test_Thread(QThread):
notify_progress = pyqtSignal(str)
def __init__(self, parent=None):
QThread.__init__(self, parent)
def create_items(self):
for elem in xrange(190000):
yield elem
def run(self):
for i in self.create_items():
self.notify_progress.emit(str(i))
class MyCustomDialog(QDialog):
def __init__(self):
super(MyCustomDialog, self).__init__()
layout = QVBoxLayout(self)
self.tree = QTreeWidget(self)
self.pushButton_start = QPushButton("Start", self)
self.pushButton_close = QPushButton("Close", self)
layout.addWidget(self.tree)
layout.addWidget(self.pushButton_start)
layout.addWidget(self.pushButton_close)
self.test_task = Test_Thread()
self.test_task.notify_progress.connect(self.fill_tree_widget)
self.pushButton_start.clicked.connect(self.on_start)
self.pushButton_close.clicked.connect(self.close)
def fill_tree_widget(self, i):
parent = QTreeWidgetItem(self.tree)
parent.setText(0, "Number: {}".format(i))
parent.setCheckState(0, Qt.Unchecked)
parent.setFlags(parent.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)
def on_start(self):
self.test_task.start()
def main():
app = QApplication(sys.argv)
window = MyCustomDialog()
window.resize(600, 400)
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()