包含头文件:
#include <QMenu>
#include <QAction>
在类定义中增加一个QMenu对象指针:
QMenu *table_widget_menu;
在父窗体构造函数中允许QTableWidget接收QWidget::customContextMenuRequested()信号。
ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
生成所需要的右键菜单。
table_widget_menu = new QMenu(ui->tableWidget);
QAction *action = new QAction("Insert", this);
connect(action, SIGNAL(triggered()), this, SLOT(slotActionInsert()));
table_widget_menu->addAction(action);
action = new QAction("Remove", this);
connect(action, SIGNAL(triggered()), this, SLOT(slotActionRemove()));
table_widget_menu->addAction(action);