一、效果预览
二、代码
cpp文件
//listView右键菜单
void MainWindow::Rightclicklistview()
{
//初始化一级菜单
TotalRightclick =new QMenu(this);
AddDevice = new QMenu(this);
upDevice = new QAction(this);
DownDevice = new QAction(this);
Delete = new QAction(this);
EditDevice = new QAction(this);
//初始化二级菜单
DeviceIS6201A =new QMenu(this);
DeviceIS6202A = new QMenu(this);
DeviceIS6203A = new QMenu(this);
//初始化三级菜单
DeviceIS6201A_IIC = new QAction(this);
DeviceIS6201A_PMBV1 = new QAction(this);
DeviceIS6201A_PMBV2= new QAction(this);
//各级图标
//一级图标
QIcon iconadd = QIcon(":/Res/tools/add.png"); //加载图片
QIcon iconUp = QIcon(":/Res/tools/moveup.png"); //加载图片
QIcon iconDown = QIcon(":/Res/tools/movedown.png"); //加载图片
QIcon iconDelete = QIcon(":/Res/tools/delete.png"); //加载图片
QIcon iconEdit = QIcon(":/Res/tools/paste.png"); //加载图片
//二级图标
QIcon iconUser = QIcon(":/Res/tools/user.png"); //加载图片
//三级图标
QIcon iconChip = QIcon(":/Res/tools/xinpian.png"); //加载图片
//子对象在父对象里面从属关系匹配
AddDevice = TotalRightclick->addMenu(iconadd," Add Device");
upDevice = TotalRightclick->addAction(iconUp," Move Up Device");
DownDevice = TotalRightclick->addAction(iconDown," Move Down Device");
Delete = TotalRightclick->addAction(iconDelete," Delete Device");
EditDevice = TotalRightclick->addAction(iconEdit," Edit Device");
DeviceIS6201A = AddDevice->addMenu(iconUser," IS6201A");
DeviceIS6202A = AddDevice->addMenu(iconUser," IS6202A");
DeviceIS6203A = AddDevice->addMenu(iconUser," IS6203A");
DeviceIS6201A_IIC = DeviceIS6201A->addAction(iconChip, " IS6201A_IIC");
DeviceIS6201A_PMBV1 = DeviceIS6201A->addAction(iconChip," IS6201A_PMBV1");
DeviceIS6201A_PMBV2= DeviceIS6201A->addAction(iconChip, " IS6201A_PMBV2");
//给动作设置信号槽
connect( upDevice, &QAction::triggered, [=]()
{
qDebug()<<"I'm upDevice";
});
connect( DownDevice, &QAction::triggered, [=]()
{
qDebug()<<"I'm DownDevice";
});
//给动作设置信号槽
connect( Delete, &QAction::triggered, [=]()
{
}
qDebug()<<"I'm DeleteAction";
});
connect( EditDevice, &QAction::triggered, [=]()
{
qDebug()<<"I'm btnSecondAction";
});
connect( DeviceIS6201A_PMBV1, &QAction::triggered, [=]()
{
qDebug()<<"I'm DeviceIS6201A_PMBV1";
});
connect( DeviceIS6201A_PMBV2, &QAction::triggered, [=]()
{
qDebug()<<"I'm DeviceIS6201A_PMBV2";
});
//绑定控件显示右键菜单给控件设置上下文菜单策略
ui->listView->setContextMenuPolicy(Qt::CustomContextMenu);
//鼠标右键点击控件时会发送一个void QWidget::customContextMenuRequested(const QPoint &pos)信号
//给信号设置相应的槽函数
connect(ui->listView,&QLabel::customContextMenuRequested,[=](const QPoint &pos)
{
qDebug()<<pos;//参数pos用来传递右键点击时的鼠标的坐标,这个坐标一般是相对于控件左上角而言的
TotalRightclick->exec(QCursor::pos());
});
}
h文件
private:
void Rightclicklistview();
// 声明动作
QAction * upDevice;
QAction * DownDevice;
QAction * Delete;
QAction * EditDevice;
QAction * DeviceIS6201A_IIC;
QAction * DeviceIS6201A_PMBV1;
QAction * DeviceIS6201A_PMBV2;
//声明菜单
QMenu * TotalRightclick;
QMenu * AddDevice;
QMenu * DeviceIS6201A;
QMenu * DeviceIS6202A;
QMenu * DeviceIS6203A;
文档解释参考一
参考二
参考三