1

Main 与由单独模块定义的 GUI 交互。Main 中使用了两种替代方法来定义 QShortcut 的插槽。lambda 方法有效(但看起来很麻烦)。只有先执行 lambda 方法,直接方法才有效。如果带有 lambda 方法的行被注释掉,那么直接方法将失败(没有错误消息)。为什么单独使用直接方法会失败?

''' # p.py

import sys
from PyQt5 import QtWidgets as qtw
from Q import MainWindow

class MyActions():
    def __init__(self, my_window):
        self.my_window = my_window

        self.my_window.run.activated.connect(lambda: self.rmssg1()) # had to use this as a work-around
        self.my_window.run.activated.connect(self.rmssg2)           # expected this to work

    def rmssg1(self):
        self.my_window.my_label1.setText('Ctrl+R pressed -> mssg 1')

    def rmssg2(self):
        self.my_window.my_label2.setText('Ctrl+R pressed -> mssg 2')

if __name__ == '__main__':
    app = qtw.QApplication(sys.argv)
    mw = MainWindow()
    MyActions(mw)
    mw.show()
    sys.exit(app.exec())

''' 这是一个单独模块中的 GUI

''' #q.py

import sys
from PyQt5 import QtWidgets as qtw
from PyQt5.QtGui import QKeySequence

class MainWindow(qtw.QMainWindow):
    def __init__(self, parent=None):
        super().__init__()

        self.my_label1 = qtw.QLabel("Enter Ctrl+R", self)
        self.my_label1.setGeometry(20,20,200,30)

        self.my_label2 = qtw.QLabel("Enter Ctrl+R", self)
        self.my_label2.setGeometry(20, 50, 200, 30)

        #define shortcut
        self.run = qtw.QShortcut(QKeySequence('Ctrl+R'), self)

'''

4

1 回答 1

1

问题很简单:当您MyActions(mw)没有为对象分配变量以致内存丢失时,解决方案是:

if __name__ == '__main__':
    app = qtw.QApplication(sys.argv)
    mw = MainWindow()
    foo = MyActions(mw)
    mw.show()
    sys.exit(app.exec())
于 2020-08-30T18:54:52.383 回答