PyQt5为QShortcut在单独的模块中定义插槽



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

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

''

问题很简单:当你执行MyActions(mw)时,不给对象分配变量,这样内存就会丢失,解决方案是:

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

相关内容

  • 没有找到相关文章

最新更新