【问题标题】:Calling a Slot by QtCore.SignalMapper通过 QtCore.SignalMapper 调用插槽
【发布时间】:2014-03-28 10:48:47
【问题描述】:

我想通过具有不同参数的相同函数检查用户在几个 QtGui.QLineEdits 中的输入。我试过 QtCore.SignalMapper。这是我在测试应用程序中的代码:

    self.signalMapper = QtCore.QSignalMapper(self)
    QtCore.QObject.connect(self.lineEdit_331, QtCore.SIGNAL(_fromUtf8('returnPressed()')), self.signalMapper.map)
    QtCore.QObject.connect(self.lineEdit_341, QtCore.SIGNAL(_fromUtf8("returnPressed()")), self.signalMapper.map)
    self.signalMapper.setMapping(self.lineEdit_331,'links')
    self.signalMapper.setMapping(self.lineEdit_341,'rechts')
    QtCore.QObject.connect(self.signalMapper, QtCore.SIGNAL(_fromUtf8("mapped(QString)")),self.test)

signalMapper 存在且所有连接都返回“True”,但不调用槽(更改“连接”和“设置映射”的顺序后相同)。 将 lineEdits 信号连接到插槽工作:

    QtCore.QObject.connect(self.lineEdit_331, QtCore.SIGNAL(_fromUtf8("returnPressed()")), self.test_1)

我的代码有什么问题?感谢您的帮助

【问题讨论】:

    标签: python pyqt4 signals-slots


    【解决方案1】:

    您的代码的主要问题是您使用丑陋、容易出错的旧式语法来连接信号,而不是 new-style syntax

    这是对您的示例代码的重写:

        self.signalMapper = QtCore.QSignalMapper(self)
        self.lineEdit_331.returnPressed.connect(self.signalMapper.map)
        self.lineEdit_331.returnPressed.connect(self.signalMapper.map)
        self.signalMapper.setMapping(self.lineEdit_331, 'links')
        self.signalMapper.setMapping(self.lineEdit_341, 'rechts')
        self.signalMapper.mapped[str].connect(self.test)
    

    如果您好奇为什么您的原始代码不起作用,那是因为您应该在前两个连接中使用了 SLOT。应该是:

        QtCore.QObject.connect(
            self.lineEdit_331, QtCore.SIGNAL('returnPressed()'),
            self.signalMapper, QtCore.SLOT('map()'))
    

    这是因为QSignalMapper.map 有两个重载,因此您需要指定要使用哪一个。

    【讨论】:

    • 您在新式语法中的重写工作,感谢您的提示,按照您的描述完成的旧式语法不起作用。在使用旧式语法之前,我尝试了新式但没有成功。您提供了解释:我忘记了最后一行中的“[str]”。
    • @user3455890。好奇的。我在您的问题中测试了确切的代码,并且使用 SLOT 是唯一可以为我修复它的方法。但也许这取决于 pyqt/sip 的版本,或者什么...
    • 我想,这是最后一次连接中的 Qstring,看这里:stackoverflow.com/questions/1400858/…。我在我的测试应用程序中添加了“尝试/除外”,它可以工作。所以最重要的提示是你的'[str]',感谢你的支持,从现在开始我使用新式语法:-)
    猜你喜欢
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多