gpt4 book ai didi

python-3.x - 为什么 pyqtSlot 装饰器会导致 "TypeError: connect() failed"?

转载 作者:行者123 更新时间:2023-12-04 01:37:52 30 4
gpt4 key购买 nike

我有这个带有 PyQt5 的 Python 3.5.1 程序和一个从 QtCreator ui 文件创建的 GUI,其中 pyqtSlot 装饰器导致“TypeError:connect() 在 textChanged(QString) 和edited() 之间失败”。

在重现问题的示例代码中,我有 2 个自定义类:MainApp 和 LineEditHandler。 MainApp 实例化主 GUI(来自文件“mainwindow.ui”)并且 LineEditHandler 处理 QLineEdit 对象。 LineEditHandler 存在的原因是将主要与 QLineEdit 对象相关的自定义方法集中在一个类中。它的构造函数需要 QLineEdit 对象和 MainApp 实例(在需要时访问其他对象/属性)。

在 MainApp 中,我将 QLineEdit 的 textChanged 信号连接到 LineEditHandler.edited()。如果我不使用 pyqtSlot() 装饰 LineEditHandler.edited() 一切正常。如果我确实使用 @pyqtSlot() 作为该方法,则代码运行将失败,并显示“TypeError:connect() 在 textChanged(QString) 和 Edited() 之间失败”。我在这里做错了什么?

您可以在以下位置获取 mainwindow.ui 文件:https://drive.google.com/file/d/0B70NMOBg3HZtUktqYVduVEJBN2M/view

这是生成问题的示例代码:

import sys
from PyQt5 import uic
from PyQt5.QtWidgets import *
from PyQt5.QtCore import pyqtSlot


Ui_MainWindow, QtBaseClass = uic.loadUiType("mainwindow.ui")


class MainApp(QMainWindow, Ui_MainWindow):

def __init__(self):
# noinspection PyArgumentList
QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)

# Instantiate the QLineEdit handler.
self._line_edit_handler = LineEditHandler(self, self.lineEdit)
# Let the QLineEdit handler deal with the QLineEdit textChanged signal.
self.lineEdit.textChanged.connect(self._line_edit_handler.edited)


class LineEditHandler:

def __init__(self, main_window, line_edit_obj):
self._line_edit = line_edit_obj
self._main_window = main_window

# FIXME The pyqtSlot decorator causes "TypeError: connect() failed between
# FIXME textChanged(QString) and edited()"
@pyqtSlot(name="edited")
def edited(self):
# Copy the entry box text to the label box below.
self._main_window.label.setText(self._line_edit.text())


def main():
app = QApplication(sys.argv)
window = MainApp()
window.show()
sys.exit(app.exec_())


if __name__ == "__main__":
main()

最佳答案

为什么要使用@pyqtSlot ?

失败的原因是LineEditHandler不是 QObject .什么 @pyqtSlot do 基本上是创建一个真正的 Qt 插槽,而不是在内部使用代理对象(这是没有 @pyqtSlot 的默认行为)。

关于python-3.x - 为什么 pyqtSlot 装饰器会导致 "TypeError: connect() failed"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40674940/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com