QTableWidget学习

本文介绍如何在Qt中为TableWidget设置右键菜单,包括打开、删除和退出选项,以及如何通过代码添加项目到TableWidget。同时,提供了清空已有项目的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、这次项目需要用到,可以在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);  //打开指定目录,并选定指定文件 }

2、为tablewidget添加项目

ui.tableWidget_2->setItem(j*fileNameList.size() + i,0,new QTableWidgetItem(QString::number(chosedCarNum[j])));

在添加项目前如果需要清空之前添加的项目则加如下代码:

int rowCount = ui.tableWidget_2->rowCount();
for (int i = rowCount - 1; i >= 0; i--)
  ui.tableWidget_2->removeRow(i);

 

转载于:https://www.cnblogs.com/xian-yongchao/p/9648227.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值