QTableWidget学习

一、这次项目需要用到,可以在tablewidget中添加item,并且可以通过鼠标的右键选项进行一些打开、删除等操作。

1、在构造函数中定制右键菜单选项

ui.tableWidget_2->setSelectionBehavior(QAbstractItemView::SelectRows); //设置选择行为,以行为单位
ui.tableWidget_2->setSelectionMode(QAbstractItemView::SingleSelection); //设置选择模式,选择单行
openAction = new QAction("打开文件",this);
deleteAction = new QAction("删除文件", this);
closeAction = new QAction("退出菜单",this);
openAction->setShortcut(QKeySequence::Open);//设置打开快捷键
deleteAction->setShortcut(QKeySequence::Delete);
closeAction->setShortcut(QKeySequence::Quit);
ui.tableWidget_2->setContextMenuPolicy(Qt::CustomContextMenu);//设置上下文显示菜单的方式,Qt::CustomContextMenu是唯一与右键菜单相关的参数。
pMenu = new QMenu(ui.tableWidget_2);
pMenu->addAction(openAction);
pMenu->addAction(deleteAction);
pMenu->addAction(closeAction);
    
connect(openAction, SIGNAL(triggered(void)), this, SLOT(openActionSlot(void)));
connect(deleteAction, SIGNAL(triggered(void)), this, SLOT(deleteActionSlot(void)));
connect(closeAction, SIGNAL(triggered(void)), this, SLOT(closeActionSlot(void)));
/*This signal is emitted when the widget's contextMenuPolicy is Qt::CustomContextMenu, and the user has requested a context menu on the widget*/
connect(ui.tableWidget_2, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(customContextMenuRequestedSlot(QPoint)));  //customContextMenuRequested(QPoint)信号是鼠标右击的时候产生的(注意,contextMenuPolicy必须是Qt::CustomContextMenu, 并且用户已经请求了一个上下文菜单


/*如下是一些槽函数的定义*/
void MyFtp::customContextMenuRequestedSlot(QPoint point) { pMenu->exec(QCursor::pos()); //运行并且显示右键菜单栏 } void MyFtp::openActionSlot(void) { int row = ui.tableWidget_2->currentRow(); if (row!=-1) chosedFilePath = ui.tableWidget_2->item(row,1)->text(); QProcess process; //process.startDetached(QString("explorer.exe /select,"+chosedFilePath));//注意,在切换盘符的时候将无法获取正确结果 #ifdef WIN32 chosedFilePath.replace("/", "\\"); //***这句windows下必要*** #endif process.startDetached("explorer /select," + chosedFilePath);  //打开指定目录,并选定指定文件 }

 

posted @ 2018-09-14 18:23  xianyongchao  阅读(438)  评论(0编辑  收藏  举报