我们说我有这段代码:
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_MainWidow
和Ui_Hi
类pyuic5
。
答案 0 :(得分:0)
我不需要直接连接到self.h.update_label
。我必须连接到MainWindow内部的方法update_label_hello
到doIt
,然后将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)