此文以设置QListWidget的自定义菜单为例,其他继承于QWidget的类也都可以按类似的方法去实现。
1、ui文件设置contextMenuPolicy属性为CustomContextMenu
2、添加槽函数
/**
* @brief onCustomContextMenuRequested 右键弹出菜单
* @param pos 右键的坐标
*/
void onCustomContextMenuRequested(const QPoint &pos);
/**
* @brief onDeleteMediaFolderTriggered 删除选中配置
*/
void onDeleteMediaFolderTriggered();
void Xxxx::onCustomContextMenuRequested(const QPoint &pos)
{
QListWidgetItem *item = ui->listWidget->itemAt(pos);
if (item != NULL)
{
QMenu menu(this);
QAction actionDelete("删除", this);
connect(&actionDelete, &QAction::triggered, this, &Xxxx::onDeleteMediaFolderTriggered);
menu.addAction(&actionDelete);
// 可以添加更多的菜单选项
//QAction actionXxxx("xxxx", this);
//connect(&actionXxxx, &QAction::triggered, this, &Xxxx::onXxxxMediaFolderTriggered);
//menu.addAction(&actionXxxx);
menu.exec(QCursor::pos());
}
}
void Xxxx::onDeleteMediaFolderTriggered()
{
int row = ui->listWidget->currentRow();
if (row < 0 || row > ui->listWidget->count())
{
return;
}
QListWidgetItem *item = ui->listWidget->takeItem(row);
if (item != NULL)
{
delete item;
item = NULL;
}
}
3、连接信号槽
connect(ui->listWidget, &QListWidget::customContextMenuRequested, this, &Xxxx::onCustomContextMenuRequested);
打完收工!