PyQt用dict发出信号

时间:2017-05-14 14:01:22

标签: python python-3.x qt pyqt pyqt5

我想发出定义的信号:

finished = pyqtSignal(dict)

# other place it's connected to function:
def finised(self, dict_result):

我称之为self.finished.emit({"bk": {}})并且它有效 现在我用self.finished.emit({2: {}})称呼它并且它不起作用!!

  

追踪(最近一次通话):     文件" /home/sylwek/workspace/t2-pv/Manager.py" ;,第452行,在运行中       self.finished.emit({2:{}})   TypeError:TesterManager.finished [dict] .emit():参数1具有意外类型' dict'

这是正常的吗?我可以将{2: {}}更改为{'2': {}},但我想了解原因,并确保不会有任何其他意外!

我使用PyQt 5.8.2-2和python 3.6.1-1

编辑(添加工作示例):

from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QApplication


class Emiterer(QtCore.QThread):
    f = QtCore.pyqtSignal(dict)

    def __init__(self):
        super(Emiterer, self).__init__()

    def run(self):
        self.f.emit({"2": {}})
        # self.f.emit({2: {}})  < == this don't work!


class Main(QtWidgets.QMainWindow):

    def __init__(self):
        super(Main, self).__init__()
        self.e = Emiterer()
        self.e.f.connect(self.finised)
        self.e.start()

    def finised(self, r_dict):
        print(r_dict)


if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    m = Main()
    m.show()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:9)

object定义中使用dict代替pyqtSignal。 E.g。

class Emiterer(QtCore.QThread):
    f = QtCore.pyqtSignal(object)

原因是定义为pyqtSignal(dict)的信号实际上被PyQt5解释为pyqtSignal('QVariantMap'),而QVariantMap只能将字符串作为键。

您可以使用

检查此(针对您的特定课程)
m = Emiterer.staticMetaObject
method = m.method(m.methodCount() - 1)  # the last defined signal or slot
print(method.methodSignature())

这将打印PyQt5.QtCore.QByteArray(b'f(QVariantMap)')