QT实现鼠标右键快捷菜单(QTableWidget)

时间:2024-03-14 15:14:43

对于右键点击事件,这里用到的是Qt::CustomContextMenu方法,本例通过右点QTableWidget,显示下拉菜单,同时获得点击的行号。 
ui界面如下图: 
QT实现鼠标右键快捷菜单(QTableWidget) 
//customContextMenuRequested(QPoint)信号是QWidget中唯一右键菜单点击的信号,该信号发出的条件是:widget的ContextMenuPolicy必须是Qt::CustomContextMenu,此时右键点击就会发出此信号。

ui->tableWidget->setContextMenuPolicy (Qt::CustomContextMenu); 
connect(ui->tableWidget,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(show_menu(QPoint)));

void Widget::show_menu(const QPoint pos) 

//设置菜单选项 
QMenu *menu = new QMenu(ui->tableWidget); 
QAction *pnew = new QAction(“第一项”,ui->tableWidget); 
QAction *pnew1 = new QAction(“第二项”,ui->tableWidget); 
connect (pnew,SIGNAL(triggered()),this,SLOT(clickgoose())); 
connect (pnew1,SIGNAL(triggered()),this,SLOT(clickmms())); 
menu->addAction(pnew); 
menu->addAction(pnew1); 
menu->move (cursor ().pos ()); 
menu->show (); 
//获得鼠标点击的x,y坐标点 
int x = pos.x (); 
int y = pos.y (); 
QModelIndex index = ui->tableWidget->indexAt (QPoint(x,y)); 
int row = index.row ();//获得QTableWidget列表点击的行数 
}