我是靠谱客的博主 帅气鞋垫,最近开发中收集的这篇文章主要介绍qmenu基本用法,如何将QActions列表添加到QMenu并使用单个插槽处理它们?,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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.

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.

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

解决方案

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.

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

}

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

最后

以上就是帅气鞋垫为你收集整理的qmenu基本用法,如何将QActions列表添加到QMenu并使用单个插槽处理它们?的全部内容,希望文章能够帮你解决qmenu基本用法,如何将QActions列表添加到QMenu并使用单个插槽处理它们?所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(59)

评论列表共有 0 条评论

立即
投稿
返回
顶部