如何确定QAction的来源? [英] How to determine the source of an QAction?

查看:576
本文介绍了如何确定QAction的来源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何简单/优雅的方式来确定QAction的来源?
我的意思是我有一个QAction被添加到多个QWidgets(与 QWidget :: addAction ),当动作的触发信号被发出时,我需要知道哪个QWidget是源,因为我需要查询该特定的部件。

I want to know if there is any easy/elegant way to determine the source of an QAction? What I mean I have one QAction which is added to multiple QWidgets (with QWidget::addAction) and when the triggered signal of the action gets emitted I need to know which QWidget is the source because I need to query that specific widget.

我没有看到任何方法来做这个与QAction本身,父母总是相同的,无论从哪里动作被触发。

I don't see any way to do this with the QAction itself, the parent is always the same no matter from where the actions gets triggered.

不得不解决这个是保存一个全局指针到活动的小部件,但再次似乎没有优雅的方式在Qt捕获事件当一个小部件收到焦点设置为活动的。

The idea I had to solve this was to save a global pointer to the active widget, but again there seems to be no elegant way in Qt to capture the event when a widget receives the focus to set it as the active one.

另一种方法是为每个小部件使用不同的QActions,但在我的情况下,最好使用一个,因为用户可以自定义动作的快捷方式,我不认为这是好的设计具有多个具有相同快捷键和文本等的动作,它们都具有相同的但对不同的小部件进行操作。

Another way would be to use different QActions for each widget, but in my case it's better to use one because the user can customize the shortcuts of the actions and I don't think it's good design to have multiple actions with the same shortcuts and text etc. which all do the same but operate on different widgets.

PS:大多数动作可以通过快捷方式

P.S.: Most of the actions can be triggered either by shortcut (with widget context enabled so the widget need focus anyways) and also from a custom context menu on that widget.

我可以提供一个简单的代码示例,如果这有助于理解我的问题:

I can provide a simple code example if that helps to understand my problem:

// init the action etc.
void Widget::init()
{
    QAction *action = new QAction("Do Something");
    action->setShortcut("Ctrl+X");
    action->setShortcutContext(Qt::WidgetShortcut);
    connect(action, SIGNAL(triggered()), SLOT(action_triggered()));

    // assume the widgets 1 to 3 already exist (type QWidget* off course)
    widget1->addAction(action);
    widget2->addAction(action);
    widget3->addAction(action);
}

// SLOT action_triggered()
void Widget::action_triggered()
{
    QWidget *source;
    // TODO: which widget is the source: widget1, widget2 or widget3?
}


推荐答案

code> QAction associatedWidgets 方法来确定添加了操作的窗口小部件的列表。然后,您可以检查此列表中当前具有焦点的窗口小部件。

I think you can use QAction associatedWidgets method to determine the list of widgets, to which action was added. Then you can examine this list for widget, that currently has focus.

QList <QWidget *> widget_list = sender()->associatedWidgets();

for(int i = 0; i != widget_list.size(); ++i) {
    if (widget_list.at(i)->hasFocus()){
        sourceWidget = widget_list.takeAt(i);
        break;
    }
}

这篇关于如何确定QAction的来源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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