pyqtSignal()连接bool对象而不是str

时间:2016-09-09 18:39:31

标签: python qt pyqt5

我们说我有这段代码:

from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QDialog
from PyQt5.QtCore import pyqtSignal
from ui_helloworld import Ui_MainWindow
from ui_hellodialog import Ui_Hi
from sys import argv
from sys import exit


class MainWindow(QMainWindow):

    update = pyqtSignal(str)

    def __init__(self):

        super(MainWindow, self).__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.h = HelloDialog()

        self.ui.pushButton.clicked.connect(self.update_label)
        self.ui.doIt.clicked.connect(self.h.update_label)

    def update_label(self):
        self.h.show()

    def update_label_hello(self, msg):

        self.update.emit(msg)


class HelloDialog(QDialog):

    def __init__(self):

        super(HelloDialog, self).__init__()
        self.ui = Ui_Hi()
        self.ui.setupUi(self)

    def update_label(self, msg):

        print msg

        # Crashes the program:
        # TypeError: setText(self, str): argument 1 has unexpected type 'bool'
        # >> self.ui.label.setText(msg)


        self.ui.label.setText("Hello world!")


def main():

    app = QApplication(argv)

    window = MainWindow()
    window.show()

    exit(app.exec_())


if __name__=="__main__":
    main()

这很简单。它是2个窗口,一个是QMainWindow,另一个是QDialog。 MainWindow有2个按钮,pushButton和doIt:

  • pushButton打开HelloDialog
  • doIt发出update信号

问题是,HelloDialog中的插槽是从update中的MainWindow信号接收到的布尔值,但我将其声明为str对象。

为什么update_label广告位会收到bool而不是str个对象?

localhost :: Documents/Python/qt » python main.py 

{ push `doIt` object }

False

生成Ui_MainWidowUi_Hipyuic5

1 个答案:

答案 0 :(得分:0)

我不需要直接连接到self.h.update_label。我必须连接到MainWindow内部的方法update_label_hellodoIt,然后将pyqtSignal连接到HelloDialog

中的插槽

所以,最终结果如下:

初始化MainWindow

def __init__(self):

    super(MainWindow, self).__init__()

    self.ui = Ui_MainWindow()
    self.ui.setupUi(self)
    self.h = HelloDialog()

    self.ui.pushButton.clicked.connect(self.update_label_)
    self.ui.doIt.clicked.connect(self.update_label_hello)

    self.update.connect(self.h.update_label)