Qt工作笔记-QTreeWidgetItem中type的基本用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq78442761/article/details/79797211


这是一个很好的东西。

话不多说,运行截图如下:



代码如下:

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QMenu>
#include <QAction>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

private slots:
    void OnListContextMenu(const QPoint& pt);

public:
    enum{THE_FIST,THE_SECOND,THE_THIRD,THE_FOURTH,THE_FIFTH};
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

widget.cpp

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

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    ui->treeWidget->setHeaderLabel(tr("第一列"));

    QTreeWidgetItem *newItem1=new QTreeWidgetItem(THE_FIST);
    newItem1->setText(0,"第一顶部的结点");

    QTreeWidgetItem *newItem2=new QTreeWidgetItem(THE_SECOND);
    newItem2->setText(0,"第二顶部的结点");

    QTreeWidgetItem *newItem3=new QTreeWidgetItem(THE_THIRD);
    newItem3->setText(0,"第三顶部的结点");

    QTreeWidgetItem *newItem4=new QTreeWidgetItem(THE_FOURTH);
    newItem4->setText(0,"第四顶部的结点");

    QTreeWidgetItem *newItem5=new QTreeWidgetItem(THE_FIFTH);
    newItem5->setText(0,"第五顶部的结点");

    ui->treeWidget->addTopLevelItem(newItem1);
    newItem1->addChild(newItem2);
    newItem2->addChild(newItem3);
    newItem3->addChild(newItem4);
    newItem4->addChild(newItem5);

    // 右键菜单支持
    ui->treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->treeWidget,SIGNAL(customContextMenuRequested(const QPoint&)),this,SLOT(OnListContextMenu(const QPoint&)));
}

void Widget::OnListContextMenu(const QPoint& pt){
    QMenu menu;
    if(ui->treeWidget->currentItem()->type()==THE_FIST){
       menu.addAction(tr("我是老大"));
    }
    else if(ui->treeWidget->currentItem()->type()==THE_SECOND){
        menu.addAction(tr("我是老二"));
    }
    else if(ui->treeWidget->currentItem()->type()==THE_THIRD){
        menu.addAction(tr("我是老三"));
    }
    else if(ui->treeWidget->currentItem()->type()==THE_FOURTH){
        menu.addAction(tr("我是老四"));
    }
    else{
        menu.addAction(tr("我是老五"));
    }
    menu.exec(ui->treeWidget->mapToGlobal(pt));
}

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

main.cpp

#include "widget.h"
#include <QApplication>

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

    return a.exec();
}

展开阅读全文

没有更多推荐了,返回首页