使用 QAction 而不添加到菜单(或工具栏)
我正在尝试开发一个具有非常模块化的命令方法的应用程序,并且认为这会很好,因为我正在使用 pyqt,使用 QAction 将快捷方式绑定到命令。
但是,似乎操作快捷方式仅在操作在菜单或工具栏中可见时才起作用。有谁知道如何让此操作在不可见的情况下发挥作用?
下面是一些示例代码,显示了我正在尝试的内容。
谢谢,
安德烈
from PyQt4 import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
class TesteMW(QMainWindow):
def __init__(self, *args):
QMainWindow.__init__(self, *args)
self.create_action()
def create_action(self):
self.na = QAction(self)
self.na.setText('Teste')
self.na.setShortcut('Ctrl+W')
self.connect(self.na, SIGNAL('triggered()'), self.action_callback)
# uncomment the next line for the action to work
# self.menuBar().addMenu("Teste").addAction(self.na)
def action_callback(self):
print 'action called!'
app = QApplication(sys.argv)
mw = TesteMW()
mw.show()
app.exec_()
I'm trying to develop an application with a very modular approach to commands and thought it would be nice, sind I'm using pyqt, to use QAction's to bind shortcuts to the commands.
However, it seems that actions shortcuts only works when the action is visible in a menu or toolbar. Does anyone know a way to get this action to work without it being visible?
Below some example code that shows what I'm trying.
Thanks,
André
from PyQt4 import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
class TesteMW(QMainWindow):
def __init__(self, *args):
QMainWindow.__init__(self, *args)
self.create_action()
def create_action(self):
self.na = QAction(self)
self.na.setText('Teste')
self.na.setShortcut('Ctrl+W')
self.connect(self.na, SIGNAL('triggered()'), self.action_callback)
# uncomment the next line for the action to work
# self.menuBar().addMenu("Teste").addAction(self.na)
def action_callback(self):
print 'action called!'
app = QApplication(sys.argv)
mw = TesteMW()
mw.show()
app.exec_()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要先将操作添加到小部件中,然后才会对其进行处理。来自 QAction 的 QT 文档:
这并不意味着它们将作为菜单项或其他内容可见 - 只是它们将作为小部件事件循环的一部分进行处理。
You need to add your action to a widget before it will be processed. From the QT documentation for QAction:
This does not mean that they will be visible as a menu item or whatever - just that they will be processes as part of the widgets event loop.