函数介绍

1.void setContextMenuPolicy(Qt::ContextMenuPolicy policy)

This enum type defines the various policies a widget can have with respect to showing a context menu.

Constant Value Description
Qt::NoContextMenu 0 the widget does not feature a context menu, context menu handling is deferred to the widget’s parent.
Qt::PreventContextMenu 4 the widget does not feature a context menu, and in contrast to NoContextMenu, the handling is not deferred to the widget’s parent. This means that all right mouse button events are guaranteed to be delivered to the widget itself through QWidget::mousePressEvent(), and QWidget::mouseReleaseEvent().
Qt::DefaultContextMenu 1 the widget’s QWidget::contextMenuEvent() handler is called.
Qt::ActionsContextMenu 2 the widget displays its QWidget::actions() as context menu.
Qt::CustomContextMenu 3 the widget emits the QWidget::customContextMenuRequested() signal.

示例

示例1:创建上下文菜单(createContextMenu)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// .h
public:
void createContextMenu();

protected:
void contextMenuEvent(QContextMenuEvent *e) override;

private:
QMenu *m_menu = nullptr;

// .cpp
void Widget::createContextMenu()
{
m_menu = new QMenu(ui->tableWidget);

auto actionAdd = new QAction(QIcon(), tr("增加行"));
connect(actionAdd, &QAction::triggered, this, [&](bool){ ui->tableWidget->insertRow(ui->tableWidget->rowCount()); });
m_menu->addAction(actionAdd);

auto actionIns = new QAction(QIcon(), tr("插入行"));
connect(actionIns, &QAction::triggered, this, [&](bool){
auto index = ui->tableWidget->rowCount() == 0 ? 0 : ui->tableWidget->currentRow() + 1;
ui->tableWidget->insertRow(index);
});
m_menu->addAction(actionIns);

auto actionDel = new QAction(QIcon(), tr("删除行"));
connect(actionDel, &QAction::triggered, this, [&](bool){ ui->tableWidget->removeRow(ui->tableWidget->currentRow()); });
m_menu->addAction(actionDel);

// 设置小部件的上下文菜单
ui->tableWidget->setContextMenuPolicy(Qt::ActionsContextMenu);
}

void Widget::contextMenuEvent(QContextMenuEvent *e)
{
m_menu->exec(e->globalPos());
}