Qt工作笔记-树图结构的2种方式,实现右键菜单

程序运行截图如下:

一种是使用setContextMenuPolicy然后使用信号和槽关联。
一种是重写void contextMenuEvent(QContextMenuEvent *event);

程序结构如下图:
Qt工作笔记-树图结构的2种方式,实现右键菜单_第1张图片

代码如下图:
mytreeview.h

#ifndef MYTREEVIEW_H
#define MYTREEVIEW_H

#include 

class MyTreeView : public QTreeView
{
    Q_OBJECT
public:
    MyTreeView(QWidget *parent=0);

protected:
    void contextMenuEvent(QContextMenuEvent *event);
};

#endif // MYTREEVIEW_H

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include 

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    Ui::Widget *ui;

private slots:
    void onContextMenu(const QPoint &pt);
};

#endif // WIDGET_H

main.cpp

#include "widget.h"
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

mytreeview.cpp

#include "mytreeview.h"
#include <QContextMenuEvent>
#include <QMenu>

MyTreeView::MyTreeView(QWidget *parent):
    QTreeView(parent)
{

}

void MyTreeView::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu menu;
    menu.addAction("第一个Action");
    menu.addAction("第二个Action");
    menu.exec(event->globalPos());

}

widget.cpp

#include "widget.h"
#include "ui_widget.h"

#include 

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->treeView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(onContextMenu(QPoint)));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::onContextMenu(const QPoint &pt)
{
    QMenu menu;
    menu.addAction("第一个Action");
    menu.addAction("第二个Action");
    menu.exec(ui->treeView->mapToGlobal(pt));
}

你可能感兴趣的:(C/C++,Qt,工作笔记)