PyQt5 Define the slot in a separate module for QShortcut

75 views Asked by At

Main interacts with a GUI defined by a separate module. Two alternative approaches are used in Main to define the slot for a QShortcut. The lambda method works (but seems cumbersome). The direct method works, only if the lambda method is executed first. If the line with the lambda method is commented out, then the direct method fails (with no error message). Why does the direct method alone fail?

''' # 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())

''' Here's the GUI in a separate module

''' #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)

'''

1

There are 1 answers

0
eyllanesc On BEST ANSWER

The problem is simple: When you do MyActions(mw) not assign a variable to the object so memory can be lost, the solution is:

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