QTableView是一个比较实用的类,下面教给大家如何在QTableView中添加右键菜单。
#include <QMenu>
#include <QAction>
QTableView *tableview;
QMenu *rightMenu; //右键菜单
QAction *cutAction; //剪切
QAction *copyAction; //复制
QAction *pasteAction; //粘贴
QAction *deleteAction; //删除
private slots:
void clicked_rightMenu(const QPoint &pos); //右键信号槽函数
tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);//设置单元格不可编辑
tableview->setContextMenuPolicy(Qt::CustomContextMenu); //少这句,右键没有任何反应的。
createRightMenu(); //创建一个右键菜单
connect(tableview,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(clicked_rightMenu(QPoint)));
其中createRightMenu函数:
rightMenu = new QMenu;
cutAction = new QAction("剪切",this);
copyAction = new QAction("复制",this);
pasteAction = new QAction("粘贴",this);
deleteAction = new QAction("删除",this);
rightMenu->addAction(cutAction);
rightMenu->addAction(copyAction);
rightMenu->addAction(pasteAction);
rightMenu->addAction(deleteAction);
clicked_rightMenu槽函数:
rightMenu->exec(QCursor::pos());