qt动态多级菜单

由于项目需要,这段时间需要实现类似QQ好友分组的功能,其中包括了新建分组、删除分组、重命名分组、移动好友到分组、删除好友、发送消息等,暂时列出这么一些需求吧。

    好友列表可以用QTreeWidget实现,根据父节点和子节点来建立不同的右键菜单;我们知道,建立菜单需要用到QMenu和QAction,其中QMenu建立菜单,QAction建立菜单子项,同时相应子项的相应操作(增加、删除等);现在的问题是,如果是固定的菜单,那就好办多了,但是我们事先是不知道有多少个分组的,因此需要根据当前好友列表中的分组数和分组名来建立菜单,这就需要建立动态多级菜单。

    建立动态多级菜单是简单的,但是响应动态new出来的QAction需要怎么做呢?如果是固定的菜单,连接QAction的triggered信号到对应的槽函数即可。但是动态建立的菜单子项如何连接信号到对应的槽函数呢?

    查了下QAction的API,发现动态建立出来的菜单子项无法获得具体的QAction,于是灵机一动,去查了下QMenu的API,终于让我发现了QMenu的triggerred(QAction*)信号,来看官方的API文档的解释:

void QMenu::triggered(QAction * action) [signal]

This signal is emitted when an action in this menu is triggered.【当菜单中的动作被触发时发射该信号】

... ...

Note: This signal is emitted for the main parent menu in a hierarchy. Hence, only the parent menu needs to be connected to a slot; sub-menus need not be connected.

【该信号在action的上级菜单中触发,因此,只需要将上级菜单连接到槽函数即可,子菜单不需要连接】


    也就是说,sender是menu,而不是action。那么就可以通过发送triggerred(QAction*)信号来处理子菜单中的QAction了。部分实现代码如下:

void MainWindow::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu *menu = new QMenu(ui->treeWidget);
    QAction *action = new QAction(tr("移动好友到分组"),this);
    QMenu *menuChild = new QMenu(this);
    QStringList listName;
  
 // const int COUNT = ui->treeWidget->topLevelItemCount();
 // for(int i=0; i
 // {
 //     QString strText = ui->treeWidget->topLevelItem(i).text();
 //     listName.append(strText);
 // }

    const int COUNT = listName.count();
    for(int i=0; i<COUNT; ++i)
    {
        QAction *actionGroup = new QAction(listName.at(i), this);
        menuChild->addAction(actionGroup);
    }
    connect(menuChild, SIGNAL(triggered(QAction*)),
            this, SLOT(slot_show_groupname(QAction*)));    //连接menu的triggered信号到槽函数
    action->setMenu(menuChild);
    menu->addAction(action);
    menu->exec(QCursor::pos());
}


void MainWindow::slot_show_groupname(QAction* action)
{
    QString strText = action->text();    //根据text来判断具体的action操作
    if(strText == "我的好友")
    {
        qDebug() << "我的好友";   //这里只是一个示例 
    }

    if(strText == "我的家人")
    {
        qDebug() << "我的家人";
    }

    if(strText == "陌生人")
    {
        qDebug() << "陌生人";
    }
}
转载自:http://blog.chinaunix.net/uid-29650836-id-4486572.html

猜你喜欢

转载自blog.csdn.net/u011731378/article/details/80664145