现在的位置: 首页 > 综合 > 正文

Qt中TreeView的右键菜单实现

2017年12月21日 ⁄ 综合 ⁄ 共 662字 ⁄ 字号 评论关闭

目标
1、选中TreeView中的Item,右键弹出上下文菜单

实现
1、在使用TreeView右键菜单之前,要setContextMenuPolicy并且connect上下文菜单请求信号

setContextMenuPolicy(Qt::CustomContextMenu);

connect(this,SIGNAL(customContextMenuRequested(const QPoint &)), 
this, SLOT(slotCustomContextMenu(const QPoint &)));

2、在信号处理函数里,主要做两件事
      1、获得当前选中Item中的内容      

QModelIndex index = this->currentIndex();
 
QString fileName = this->model()->data(index).toString();

      2、创建显示菜单

QMenu *menu = new QMenu;

menu->addAction(QString("Import"), this, SLOT(slotTest()));
menu->addAction(QString("Export"), this, SLOT(slotTest()));
menu->exec(QCursor::pos());

其他
1、主要参考http://qt-project.org/forums/viewthread/18343
2、目前这种做法疑有内存泄漏问题
3、这篇文章中connect时,信号和邮槽都带参数,实际实验是无法connect成功的

【上篇】
【下篇】

抱歉!评论已关闭.