使用 QAction 而不添加到菜单(或工具栏) [英] Use QAction without adding to menu (or toolbar)

查看:25
本文介绍了使用 QAction 而不添加到菜单(或工具栏)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用非常模块化的命令方法开发一个应用程序,并认为这会很好,因为我正在使用 pyqt,使用 QAction 将快捷方式绑定到命令.
但是,似乎操作快捷方式仅在操作在菜单或工具栏中可见时才有效.有没有人知道如何在不可见的情况下使此操作起作用?
下面是一些显示我正在尝试的示例代码.
谢谢,

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,

安德烈

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_()

推荐答案

在处理之前,您需要将您的操作添加到小部件.来自 QAction 的 QT 文档:

You need to add your action to a widget before it will be processed. From the QT documentation for QAction:

动作被添加到小部件使用QWidget::addAction() 或QGraphicsWidget::addAction().笔记必须将一个动作添加到一个小部件可以使用之前;这是当快捷方式应该是时也是如此全局(即 Qt::ApplicationShortcut作为 Qt::ShortcutContext).

Actions are added to widgets using QWidget::addAction() or QGraphicsWidget::addAction(). Note that an action must be added to a widget before it can be used; this is also true when the shortcut should be global (i.e., Qt::ApplicationShortcut as Qt::ShortcutContext).

这并不意味着它们将作为菜单项或其他内容可见 - 只是它们将作为小部件事件循环的一部分进行处理.

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.

这篇关于使用 QAction 而不添加到菜单(或工具栏)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆