QT实现添加右键菜单功能
目录
1.添加头文件
#include <QContextMenuEvent>
#include <QProcess>
#include <QTableView>
#include <QModelIndex>
2.添加.h文件代码
public:
QTableView *tbView1;
QStandardItemModel *model1;
protected:
virtual void contextMenuEvent(QContextMenuEvent *event); //右键菜单事件
private slots:
3.添加.cpp文件代码
void Softdog::contextMenuEvent(QContextMenuEvent *event)
{
if(!tbView1->isHidden()){ //当前在解密文件夹解密
//创建一个菜单 添加事件
QMenu *menu1 = new QMenu(tbView1);
QAction *openFile = new QAction("打开",tbView1);
QAction *deleteFile = new QAction("删除",tbView1);
QAction *cancel = new QAction("取消",tbView1);
// QMenu *menu1 = new QMenu(tWidget);
// QAction *openFile = new QAction("打开",tWidget);
// QAction *cancel = new QAction("取消",tWidget);
menu1->addAction(openFile);
menu1->addAction(deleteFile);
menu1->addAction(cancel);
// QPoint pt = tbView1->mapFromGlobal(QCursor::pos());
// openfile_rownum = tbView1->indexAt(pt).row();
QModelIndex index = tbView1->selectionModel()->currentIndex();
openfile_rownum = index.row();
// qDebug() << "openfile_rownum:" << openfile_rownum;
deletefile_rownum = openfile_rownum;
connect(openFile,SIGNAL(triggered(bool)),this,SLOT(openfile()));
connect(deleteFile,SIGNAL(triggered(bool)),this,SLOT(handle_deletefile()));
connect(cancel,SIGNAL(triggered(bool)),this,SLOT(cancel()));
//让菜单移动鼠标位置并显示
menu1->exec(QCursor::pos());
}
}
删除文件功能
void Softdog::handle_deletefile()
{
// qDebug() <<"deletefile:" << deletefile_rownum;
QString path = pathList[deletefile_rownum];
// qDebug() << "path:" << path <<";";
QString cout = QString::number( pathList.count(),10);
// qDebug() << "count:" << pathList.count();
deletefile(path);
//重新加载
read_dir(privateName,privatePath);
//并删除没有更新的最后一栏
model1->removeRow(pathList.count());
}
bool Softdog::deletefile(const QString &path)
{
if(path.isEmpty()){
return false;
}
if(deletefile_rownum == -1){
return false;
}
// QDir dir(path);
// if(!dir.exists()){
// return true;
// }
// if(deletefile_rownum >= 0){
// dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot );
// QFileInfoList fileList = dir.entryInfoList();
// foreach (QFileInfo file, fileList) {
// if(file.isFile()){ //是文件,删除
// file.dir().remove(file.fileName());
// qDebug() << file.fileName();
// QProcess *pro_del=new QProcess;
// pro_del->start("rm "+file.fileName());
// }
// else{ //递归删除
// deletefile(dir.absolutePath());
// }
// }
// }
// return dir.rmpath(dir.absolutePath()) ;
QProcess *pro_del=new QProcess;
pro_del->start("rm -rf "+path);
pro_del->waitForFinished(3000);
return true;
}