一、效果预览
二、编写目标
- 本文是在QTreeWidget的item上进行右键弹出右键菜单的使用示例。右键菜单支持多级子菜单。
- 建立多级右键菜单的数据结构和多级子菜单的动态生成方法。
- 多级QAction指向一个响应函数,在函数里区别是那个QAction被选中。并从数据结构取出对应的值。
三、源代码
本例子的代码很少,因此把代码直接附录到这里,同时提供了scdn的资源下载,资源里面包括了同样的一份代码。如果有积分直接下载会比较方便一点,避免从这里复制粘贴。
csdn资源地址为:
https://download.csdn.net/download/robert_cysy/12004955
以下为源代码:
deviceextrainfo.h
#ifndef DEVICEEXTRAINFO_H
#define DEVICEEXTRAINFO_H
#include <QList>
#include <QString>
class DeviceExtraInfo
{
public:
DeviceExtraInfo();
static QList<QString> GetChipManufacturerTypeNameList();
static QList<QString> GetLedChipTypeNameList(int manufacturer_type);
static QList<QString> GetLedColorTypeNameList();
private:
const static QList<QList<QString>> chip_type_name_array_;
const static QList<QString> chip_manufacturer_type_name_array_;
const static QList<QString> led_color_type_name_array_;
};
#endif // DEVICEEXTRAINFO_H
deviceextrainfo.cpp
#include "deviceextrainfo.h"
const QList<QString> DeviceExtraInfo::chip_manufacturer_type_name_array_= {
"child1", "child2", "child3", "child4"};
const QList<QList<QString>> DeviceExtraInfo::chip_type_name_array_ = {
{
"grandchild1"},
{
"grandchild2", "grandchild3", "grandchild4"},
{
"grandchild5", "grandchild6"},
{
"grandchild7", "grandchild8"}
};
const QList<QString> DeviceExtraInfo::led_color_type_name_array_ = {
"Red", "Green", "Blue"};
DeviceExtraInfo::DeviceExtraInfo()
{
}
QList<QString> DeviceExtraInfo::GetLedChipTypeNameList(int manufacturer_type) {
return chip_type_name_array_.at(manufacturer_type);
}
QList<QString> DeviceExtraInfo::GetChipManufacturerTypeNameList() {
return chip_manufacturer_type_name_array_;
}
QList<QString> DeviceExtraInfo::GetLedColorTypeNameList() {
return led_color_type_name_array_;
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QVBoxLayout>
#include <QTreeWidget>
#include <QMenu>