---
title: "Qt中TreeView的右键菜单实现"
author: "sony-soft"
date: "2012-08-21T06:53:00Z"
tags: []
slug: "qt-treeview"
draft: false
lastmod: "2012-08-22T13:09:11Z"
id: 1654173
url: "https://sony-soft.iteye.com/blog/1654173"
---

**目标**  
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](http://qt-project.org/forums/viewthread/18343)  
2、目前这种做法疑有内存泄漏问题  
3、这篇文章中connect时，信号和邮槽都带参数，实际实验是无法connect成功的