如何将QActions列表添加到QMenu并使用单个插槽处理它们? [英] How to add a list of QActions to a QMenu and handle them with a single slot?

查看:1082
本文介绍了如何将QActions列表添加到QMenu并使用单个插槽处理它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我有一个 QWidget 的列表,我不知道运行时间之前的长度。然后我创建一个 QListWidget ,当我显示它们,当有人点击它们我使用信号 currentItemChanged(QListWidgetItem *,QListWidgetItem *)

First, I have a list of QWidgets that I won't know the length of until runtime. I then create a QListWidget where I show them and when someone clicks them I use the signal currentItemChanged(QListWidgetItem*, QListWidgetItem*) to catch it and get the clicked item's index.

现在我想在 QMenu 。当 QMenu 及其操作被创建时,我会知道列表,但是我不能硬编码。

Now I want to do a similar thing in the QMenu. I will know the list when the QMenu and its actions get built, but I won't be able to hard code this.

如何创建操作,捕获他们的信号并将它们连接到同一个插槽,根据操作的位置(索引)在菜单列表中做不同的事情?必须有一些方法来解决这个,因为其他应用程序使用这个。我试图看看映射,但我不能得到我的头如何使用它这个。

How can I create actions, catch their signals and connect them to the same slot which does different things depending on the action's position (index) in the menu list? There must be some way to solve this since other applications use this. I tried to look at mapping but I couldn't get my head around how to use it for this.

我试图抓住 sender ,但无法从中获取任何有用的信息。

I tried to grab the sender in the slot but was not able to get any useful information from it.

推荐答案

当使用 QAction :: setData 创建并且连接信号 QMenu :: triggered(QAction *)时,为每个动作创建索引(或任何其他数据)

You can associate an index (or any other data) to each action when they are created with QAction::setData and connect the signal QMenu::triggered(QAction*) to your slot.

然后,您可以通过 QAction :: data()检索数据。 您的插槽参数的函数。

You'll then be able to retrieve the data through the QAction::data() function of your slot parameter.

MyClass::MyClass() {
    // menu creation
    for(...) {
        QAction *action = ...;
        action->setData(10);
        ...
        menu->addAction(action);
    }
    // only one single signal connection
    connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(mySlot(QAction*)));
}

void MyClass::mySlot(QAction *action) {
   int value = action->data().toInt();

}

其他方法:信号映射或使用 sender(),请参阅 Qt Quaterly中的文章< a>。

Other methods: signal mapping or the use of sender(), are explained in that article of Qt Quaterly.

这篇关于如何将QActions列表添加到QMenu并使用单个插槽处理它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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