我无法弄清楚为什么信号不起作用。在 PyQt5 中,此代码有效(不同之处在于它不是 Signal,而是 pyqtSignal)。
单击按钮时,TextEdit 应显示消息“正在连接设备”,如果将 pyside 替换为 pyqt,代码将正常工作
import sys
from PySide6.QtCore import *
from PySide6.QtWidgets import *
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
if not MainWindow.objectName():
MainWindow.setObjectName(u"MainWindow")
MainWindow.resize(188, 267)
self.centralwidget = QWidget(MainWindow)
self.centralwidget.setObjectName(u"centralwidget")
self.pushButton = QPushButton(self.centralwidget)
self.pushButton.setObjectName(u"pushButton")
self.pushButton.setGeometry(QRect(50, 140, 75, 24))
self.textEdit = QTextEdit(self.centralwidget)
self.textEdit.setObjectName(u"textEdit")
self.textEdit.setGeometry(QRect(30, 40, 104, 71))
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"MainWindow", None))
self.pushButton.setText(QCoreApplication.translate("MainWindow", u"PushButton", None))
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self, parent=None)
self.dragPos = None
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.show()
def update_text(value, textEdit):
textEdit.setText(textEdit.toPlainText() + value)
textEdit.verticalScrollBar().setValue(textEdit.verticalScrollBar().maximum())
class account(QThread):
textUpdate = Signal(str, QTextEdit)
def __init__(self):
super().__init__(parent=None)
self.textUpdate.connect(update_text)
def run(self):
print("thread is work")
self.textUpdate.emit("Connect to device\n", ui.textEdit)
if __name__ == "__main__":
app = QApplication()
acc_instance = account()
main = MainWindow()
ui = main.ui
ui.pushButton.clicked.connect(acc_instance.start)
sys.exit(app.exec_())
PS我知道覆盖运行方法不正确。
PSS 加了一个小例子