Qt入门-QTreeWidget类

     QTreeWidget类是一个以树形显示数据的控件。

示例:

window.h

#ifndef __WINDOW_H__
#define __WINDOW_H__

#include <QMainWindow>
#include <QLineEdit>
#include <QLayout>
#include <QLabel>
#include <QTreeWidget>
#include <QTreeWidgetItem>


class Window : public QMainWindow
{
	Q_OBJECT

public:
	Window(QWidget *parent = NULL):QMainWindow(parent)
	{
		tree = new QTreeWidget;
		tree->setColumnCount(1);
		tree->setHeaderLabel("Example");

		QTreeWidgetItem *note1 = new QTreeWidgetItem(QStringList("note1"));
		tree->addTopLevelItem(note1);
		
		QTreeWidgetItem *note2 = new QTreeWidgetItem(QStringList("note2"));
		tree->addTopLevelItem(note2);

		tree->expand(tree->model()->index(1, 0));

		QTreeWidgetItem *note3 = new QTreeWidgetItem(QStringList("note3"));
		tree->addTopLevelItem(note3);

		QTreeWidgetItem *childtree1 = new QTreeWidgetItem(QStringList("child1"));
		QTreeWidgetItem *childtree2 = new QTreeWidgetItem(QStringList("child2"));
		note2->addChild(childtree1);
		note2->addChild(childtree2);

		QHBoxLayout *leftLayout = new QHBoxLayout;
		leftLayout->addWidget(tree);

		QVBoxLayout *rightLayout = new QVBoxLayout;
		QLabel *lbl = new QLabel("select:");
		edt = new QLineEdit;
		rightLayout->addWidget(lbl);
		rightLayout->addWidget(edt);
		rightLayout->addStretch();

		QHBoxLayout *mainLayout = new QHBoxLayout;
		mainLayout->addLayout(leftLayout);
		mainLayout->addLayout(rightLayout);
		mainLayout->setStretch(0, 3);
		mainLayout->setStretch(1, 1);

		QWidget *mainWidget = new QWidget;
		mainWidget->setLayout(mainLayout);

		setCentralWidget(mainWidget);

		connect(tree, SIGNAL(clicked ( const QModelIndex &)), this, SLOT(clicked ( const QModelIndex &)));
	}

private:
	QTreeWidget *tree;
	QLineEdit *edt;

private slots:
	void clicked ( const QModelIndex & index )
	{
		edt->setText(tree->currentItem()->text(0));
	}


};


#endif


main.cpp

#include <QApplication>
#include <QDialog>
#include "Window.h"



int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	Window *mainWindow = new Window;

	mainWindow->resize(300, 160);
	mainWindow->setWindowTitle(QWidget::tr("Qt Test"));
	mainWindow->show();

	return a.exec();
}

编译运行,界面如图:

Qt入门-QTreeWidget类_第1张图片

代码说明:

(1)tree->setColumnCount(1); 设置树显示的列数。

(2)tree->setHeaderLabel("Example");设置树的每一列的显示标题。

(3)tree->addTopLevelItem(note1);追加一个顶层树节点。

(4)tree->expand(tree->model()->index(1, 0));展开第1行0列的节点。

(5)note2->addChild(childtree1);在节点note2下添加一个子节点childtree1。

(6)void clicked ( const QModelIndex & index );它是树单击事件。

 

你可能感兴趣的:(tree,null,qt,Signal)