PyQt5 在单独的模块中为 QShortcut 定义插槽
PyQt5 Define the slot in a separate module for QShortcut
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)
'''
问题很简单:当你MyActions(mw)
不给对象赋值时内存会丢失,解决办法是:
if __name__ == '__main__':
app = qtw.QApplication(sys.argv)
mw = MainWindow()
<b>foo = MyActions(mw)</b>
mw.show()
sys.exit(app.exec())
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)
'''
问题很简单:当你MyActions(mw)
不给对象赋值时内存会丢失,解决办法是:
if __name__ == '__main__':
app = qtw.QApplication(sys.argv)
mw = MainWindow()
<b>foo = MyActions(mw)</b>
mw.show()
sys.exit(app.exec())