python - 将旧 SIGNAL 和 SLOT 转换为新样式的正确方法?

标签 python syntax pyqt4 pyqt5 signals-slots

我目前正在尝试将旧的 Python 程序从 Python 2 转换为 Python 3,并将 PyQt4 更新为 PyQt5。该应用程序使用 PyQt5 不支持的旧式信号和槽。我已经弄清楚了大部分需要做的事情,但下面有几行我似乎无法开始工作:

self.emit(SIGNAL('currentChanged'), row, col)
self.emit(SIGNAL("activated(const QString &)"), self.currentText())
self.connect(self,SIGNAL("currentChanged(const QString&)"), self.currentChanged)

前两行,我不知道从哪里开始,因为它们似乎没有附加到任何东西上。最后一个示例我不太确定如何处理 (const QString &)。

我不完全确定如何处理这些问题,而且我仍在学习 python,但如有任何帮助,我们将不胜感激。

编辑:文档似乎并没有深入探讨这些案例,至少以我理解的方式是这样。

最佳答案

这个问题的确切答案取决于 self 是什么类型的对象。如果它是一个已经定义了这些信号的 Qt 类,那么新式语法将是这样的:

self.currentChanged[int, int].emit(row, col)
self.activated[str].emit(self.currentText())
self.currentChanged[str].connect(self.handleCurrentChanged)

但是,如果其中任何一个不是预定义的,您将需要为它们定义自定义信号,如下所示:

class MyClass(QWidget):
    # this defines two overloads for currentChanged
    currentChanged = QtCore.pyqtSignal([int, int], [str])
    activated = QtCore.pyqtSignal(str)

    def __init__(self, parent=None):
        super(MyClass, self).__init__(parent)
        self.currentChanged[str].connect(self.handleCurrentChanged)   

    def handleCurrentChanged(self, text):
        print(text)

旧式语法允许动态发射自定义信号(即无需先定义它们),但这不再可能了。使用新型语法,必须始终明确定义自定义信号。

请注意,如果为信号只定义了一个重载,则可以省略选择器:

    self.activated.emit(self.currentText())

有关更多信息,请参阅 PyQt 文档中的这些文章:

编辑:

对于您的实际代码,您需要对 currentChanged 信号进行以下更改:

  1. Multibar.py 中(第 30 行左右):

    这定义了一个自定义信号(因为 QWidget 没有它):

    class MultiTabBar(QWidget):
        # add the following line
        currentChanged = pyqtSignal(int, int)
    
  2. Multibar.py 中(第 133 行左右):

    这会发出 (1) 中定义的自定义信号:

    # self.emit(SIGNAL('currentChanged'), row, col)
    self.currentChanged.emit(row, col)
    
  3. ScWindow.py 中(第 478 行左右):

    这将连接 (1) 中定义的信号:

        # self.connect(self.PieceTab,SIGNAL("currentChanged"),self.pieceTabChanged)
        self.PieceTab.currentChanged.connect(self.pieceTabChanged)
    
  4. ItemList.py 中(第 73 行左右):

    QFileDialogalready defines this signal ,并且只有一个重载。但是插槽的名称必须更改,因为它隐藏了内置信号名称(已成为新式语法中的属性)。所以连接应该是这样的:

        # self.connect(self,SIGNAL("currentChanged(const QString&)"),self.currentChanged)
        self.currentChanged.connect(self.onCurrentChanged)
    
  5. ItemList.py 中(第 78 行左右):

    这将重命名在 (4) 中建立的连接的插槽:

        # def currentChanged(self, file):
        def onCurrentChanged(self, file):
    

关于python - 将旧 SIGNAL 和 SLOT 转换为新样式的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46876880/

相关文章:

python - QStackedLayout 中的 QScroll 区域

python - 如何在pyqt中将数据从对话框窗口检索到主窗口?

python - 生成趋势特定数据

python - 快速从句子中提取术语

syntax - XQuery 函数 : variable and expression vs FLOWR

c# - 隐式上下文相关运算符的想法。 (点)作为句法糖

python - 有没有办法将按键重新分配给 Qt 中的不同功能?

python - 导入tensorflow时出错(刚刚安装)python 3.7

python - 有没有办法向现有的 django 命令添加功能?

ruby - Ruby 中的管道符号是什么意思?