我有loadData()函数,它解析大XML文件并将数据插入QTableWidget。应用程序启动时执行功能= GUI暂停冻结,我不希望这样。这是我的WorkerThread类:
class WorkerThread(QThread):
def __init__(self):
QThread.__init__(self)
def __del__(self):
self.wait()
def run(self):
QtApp().loadData()
这就是我的尝试:
class QtApp(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.ui = uic.loadUi('gui.ui', self)
self.ui.show()
self.workerThread = WorkerThread()
self.workerThread.start()
它只是一次又一次地加载主窗口。最终应用程序崩溃。在loadData()结束时退出workerThread也无济于事。
答案 0 :(得分:0)
这是一个可能的解决方案:
class WorkerThread(QThread):
# define a new signal which will be emitted when data loading finishes
load_data_finished = pyqtSignal(list)
def __init__(self):
QThread.__init__(self)
def run(self):
# load data in new thread
self.load_data()
def load_data(self):
data = []
#
# load your data here ...
# example:
data.append(1)
data.append(2)
data.append(3)
#
# when loading data finishes, emit the signal
self.load_data_finished.emit(data)
class QtApp(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
# load UI...
self.show()
self.workerThread = WorkerThread()
# connect the thread signal to a slot defined in this class
self.workerThread.load_data_finished.connect(self.on_load_data_finished)
self.workerThread.start()
def on_load_data_finished(self, data):
print("data loaded: ", data)
app = QApplication(sys.argv)
main_window = QtApp()
app.exec _()