Qt中QTeeWidget的简单使用

时间:2021-05-23 19:34:16
//mytreewidget.h
#ifndef MYTREEWIDGET_H
#define MYTREEWIDGET_H
#include <QWidget>
class QTreeWidget;
class QTreeWidgetItem;
class MyTreeWidget : public QWidget
{
   Q_OBJECT
public:
   explicit MyTreeWidget(QWidget *parent = 0);
   
signals:
   
public slots:
   void itemDoubleClickedSlot(QTreeWidgetItem* item,int column);
   
private:
   QTreeWidget *tree;
};
#endif // MYTREEWIDGET_H


 

 

 

//mytreewidget.cpp
#include "mytreewidget.h"
#include <QTreeWidget>
#include <QIcon>
#include <QList>
#include <QMessageBox>
MyTreeWidget::MyTreeWidget(QWidget *parent) :
   QWidget(parent)
{
   tree = new QTreeWidget(this);
   //设置QTreeWidget的列数
   tree->setColumnCount(1);
   //设置QTreeWidget标题头隐藏
   tree->setHeaderHidden(true);
   //创建QTreeWidget的头节点,父节点是tree
   QTreeWidgetItem *Friend = new QTreeWidgetItem(tree, QStringList(QString(tr("好朋友"))));
   //给Friend节点增加一个子节点
   QTreeWidgetItem *hahaya = new QTreeWidgetItem(Friend);
   hahaya->setText(0, tr("hahaya"));
   hahaya->setIcon(0, QIcon(tr("hahaya.png")));
   //QTreeWidget添加节点的另一种方法
   QTreeWidgetItem *ClassMate = new QTreeWidgetItem(tree, QStringList(QString(tr("同学"))));
   //Fly是ClassMate的子节点
   QTreeWidgetItem *Fly = new QTreeWidgetItem(ClassMate, QStringList(QString(tr("fly"))));
   QTreeWidgetItem *Strange = new QTreeWidgetItem(tree);
   Strange->setText(0, tr("陌生人"));
   QList<QTreeWidgetItem*> list;
   list.append(ClassMate);
   list.append(Strange);
   tree->insertTopLevelItems(0, list);
   //展开QTreeWidget的所有节点
   tree->expandAll();
   //响应鼠标在QTreeWidget节点上的双击事件
   connect(tree, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), this, SLOT(itemDoubleClickedSlot(QTreeWidgetItem*,int)));
   this->setWindowTitle(tr("QTreeWidget的使用"));
   this->resize(200, 500);
   //设置应用程序的图标
   this->setWindowIcon(QIcon("hahaya.png"));
}
void MyTreeWidget::itemDoubleClickedSlot(QTreeWidgetItem* item,int column)
{
   QMessageBox::warning(this, tr("响应双击事件"), tr("你双击了item"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
}


 

 

 

//main.cpp
#include <QApplication>
#include <QTextCodec>
#include "mytreewidget.h"
int main(int argc, char *argv[])
{
   QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
   QApplication app(argc, argv);
   MyTreeWidget window;
   window.show();
   app.exec();
}