python - 在信号/槽中使用自定义对象(类似 PyQt_PyObject)

标签 python pyside

由于许可问题,我设法使用 PySide 而不是 PyQt。

我需要使用信号/槽机制在线程之间传递自定义对象。使用 PyQt,我可以使用 PyQt_PyObject 类型作为信号参数,但显然,这种类型在 PySide 中不存在:

TypeError: Unknown type used to call meta function (that may be a signal): PyQt_PyObject

我尝试使用object而不是PyQt_PyObject,但只有信号和插槽之间的 DirectConnection 类型才会发生这种情况:

self.connect(dummyEmitter,
             QtCore.SIGNAL("logMsgPlain(object)"),
             self._logMsgPlain,
             QtCore.Qt.DirectConnection)

使用 QueuedConnection 时,我收到错误:

QObject::connect: Cannot queue arguments of type 'object'
(Make sure 'object' is registered using qRegisterMetaType().)

我说“事情发生了”是因为到目前为止它还不起作用。我现在由于 DirectConnection 类型而收到错误:

QObject::startTimer: timers cannot be started from another thread
QPixmap: It is not safe to use pixmaps outside the GUI thread
etc ...

我该怎么办? PySide 中是否有类似 PyQt_PyObject 类型?

编辑: 这个小例子将会失败:

from PySide import QtCore, QtGui
import sys

class Object(QtCore.QObject):
    ''' A dummy emitter that send a list to the thread '''
    def emitSignal(self):
        someList = [0, 1, 2, 3]
        self.emit(QtCore.SIGNAL("aSignal(object)"), someList)

class Worker(QtCore.QObject):
    def aSlot(self, value):
        print "List: {}".format(value)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)

    worker = Worker()
    obj = Object()

    thread = QtCore.QThread()
    worker.moveToThread(thread)
    QtCore.QObject.connect(obj, QtCore.SIGNAL("aSignal(object)"), worker.aSlot)
    # The exemple will pass with the line below uncommented
    # But obviously, I can't use a DirectConnection with a worker thread and the GUI thread
    # QtCore.QObject.connect(obj, QtCore.SIGNAL("aSignal(object)"), worker.aSlot, QtCore.Qt.DirectConnection)

    thread.start()
    obj.emitSignal()

    app.exec_()

最佳答案

目前,我找到的唯一解决方案是切换到新样式的信号/槽语法:

from PySide import QtCore, QtGui
import sys

class Object(QtCore.QObject):
    aSignal = QtCore.Signal(object)
    def emitSignal(self):
        someList = [0, 1, 2, 3]
        self.aSignal.emit(someList)

class Worker(QtCore.QObject):
    def aSlot(self, value):
        print "List: {}".format(value)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)

    worker = Worker()
    obj = Object()

    thread = QtCore.QThread()
    worker.moveToThread(thread)
    obj.aSignal.connect(worker.aSlot)

    thread.start()
    obj.emitSignal()

    app.exec_()

但是我很想知道是否有旧式语法的解决方案,但目前看来还没有。

关于python - 在信号/槽中使用自定义对象(类似 PyQt_PyObject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47602743/

相关文章:

Python 查询游戏服务器

python - PySide:QTreeView 到嵌套字典

python - 使用 python 从 Azure 机器学习服务中删除并列出所有模型和部署服务

python - 使用 unstack() reshape pandas 数据框

python - Micropython 或最小 python 安装

python - 如何部署Pyside应用程序? (运行时要求?)

python - 触发 PySide QTabWidget 中选项卡的关闭事件

python - 如何将 sqlite3 模块导入 Python 2.4?

python - 在Python中添加后选择pyside listwidget项

python-3.x - PyQt 或 PySide : QTextEdit deselect all