我通过从非GUI线程到GUI线程的信号发出模型,以便创建QTableView并设置模型。不幸的是,应用程序崩溃。当我在设置 QTableView 之前发出字典并在图类中准备模型时,一切都有效。我做错了什么?我使用的是Python 3.4和PyQt 5.4.1。
以下是代码片段:
class CheckNE(QObject):
#some code ...
neTreeForEnvAlmsChanged = pyqtSignal(QStandardItemModel, QStandardItemModel)
def check_bts_envalms(self, modelEnvBscAlm): # i call it from other CheckNE member function
#some code, i'm creating modelEnvBtsAlm here...
print('Before emitting neTreeForEnvAlmsChanged')
self.neTreeForEnvAlmsChanged.emit(modelEnvBtsAlm, modelEnvBscAlm)
print('After emitting neTreeForEnvAlmsChanged')
class MainWindow(QMainWindow):
#some code ...
@pyqtSlot(QStandardItemModel, QStandardItemModel)
def retrieveTreeForEnvAlm(self, modelBtsEnv, modelBscEnv):
print('Receiving neTreeForEnvAlmsChanged')
dialogTableWorker = TableDialog(modelBtsEnv, modelBscEnv)
print('Before showing dialog')
dialogTableWorker.show_table_dialog()
print('After showing dialog')
class TableDialog(QDialog, Ui_Dialog_Table):
def __init__(self, modelBts, modelBsc):
print('Beginning init of TableDialog')
super(TableDialog, self).__init__()
self.setupUi(self)
self.tableView.setModel(modelBts) # tableView created in Qt Designer
print('Ending init of TableDialog')
def show_table_dialog(self):
print('Showing TableDialog started')
self.exec_()
print('Showing TableDialog ended')
def main():
app = QApplication(sys.argv)
main_window = MainWindow()
checkNeWorker = CheckNE()
checkNeWorkerThread = QThread()
main_window.show()
main_window.raise_()
checkNeWorker.moveToThread(checkNeWorkerThread)
checkNeWorker.neTreeForEnvAlmsChanged.connect(main_window.retrieveTreeForEnvAlm)
checkNeWorkerThread.start()
app.exec_()
main()
结果:
Before emitting neTreeForEnvAlmsChanged
After emitting neTreeForEnvAlmsChanged
Process finished with exit code -1073741819 (0xC0000005)
但是当我使用断点进行调试时:
print('Before emitting neTreeForEnvAlmsChanged')
一切都像魅力一样工作:
Before emitting neTreeForEnvAlmsChanged
Receiving neTreeForEnvAlmsChanged
Beginning init of TableDialog
After emitting neTreeForEnvAlmsChanged
Ending init of TableDialog
Before showing dialog
Showing TableDialog started
Showing TableDialog ended
After showing dialog
当你声明信号和插槽时,你需要引用这些类型,因为它们不是python类型,但它们是在C++级别定义的。正如文档所说:定义信号C++特征的类型。每个类型可以是 Python 类型对象,也可以是作为C++类型名称的字符串。
pyqtSignal('QStandardItemModel', 'QStandardItemModel')
和
@pyqtSlot('QStandardItemModel', 'QStandardItemModel')
应该解决您的问题。