我正在尝试创建一组状态机来处理PyQt项目中的不同任务,在处理需要在单个线程上处理图形的方式的过程中,我创建了两种类型的状态机,一个StateMachine
必须继承QObject
,一个ThreadedStateMachine
为了避免重复代码,我从StateMachine
和QThread
都继承了。>
这是我复制问题的最低限度的代码:
from PyQt5.QtCore import QObject, QThread
class StateMachine(QObject):
def __init__(self):
super().__init__()
class ThreadedStateMachine(StateMachine, QThread):
def __init__(self):
super().__init__()
if __name__ == "__main__":
t = ThreadedStateMachine()
我希望它可以正常工作,但是我收到了这个异常
QObject::connect: No such signal ThreadedStateMachine::started()
Traceback (most recent call last):
File "/snap/pycharm-community/132/helpers/pydev/pydevd.py", line 1758, in <module>
main()
File "/snap/pycharm-community/132/helpers/pydev/pydevd.py", line 1752, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "/snap/pycharm-community/132/helpers/pydev/pydevd.py", line 1147, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/snap/pycharm-community/132/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/home/aaron/.PyCharmCE2019.1/config/scratches/emerson_pmd/new/scratch_7.py", line 15, in <module>
t = ThreadedStateMachine()
File "/home/aaron/.PyCharmCE2019.1/config/scratches/emerson_pmd/new/scratch_7.py", line 11, in __init__
super().__init__()
File "/home/aaron/.PyCharmCE2019.1/config/scratches/emerson_pmd/new/scratch_7.py", line 6, in __init__
super().__init__()
File "/snap/pycharm-community/132/helpers/pydev/_pydev_bundle/pydev_monkey_qt.py", line 181, in __init__
self.started = StartedSignalWrapper(self, self.started)
File "/snap/pycharm-community/132/helpers/pydev/_pydev_bundle/pydev_monkey_qt.py", line 151, in __init__
self.original_started.connect(self._signal)
TypeError: connect() failed between started() and _signal()
将QObject
和QThread
类组合为单个对象的正确方法是什么?
我目前正在使用threading.Thread
作为解决方法,但是我希望能够从另一个线程启动QMessageBox
,这显示了一个错误:
QObject::connect: Cannot queue arguments of type 'QItemSelection'
(Make sure 'QItemSelection' is registered using qRegisterMetaType().)
QBasicTimer::start: Timers cannot be started from another thread
我相信在这里可以使用QThread
。
答案 0 :(得分:0)
您有问题PyQt不允许2 QObject的双重继承,StateMachine是QObject,QThread也是QObject(请参见docs)。
我不认为问题是由threading.Thread()引起的,我怀疑这是由于您正在修改存在于线程中且不是线程安全的某些对象而导致的,QObjects不是线程安全的,所以您必须在它们所在的线程中与这些对象进行交互,并且这些模型是QObject。
阅读: