#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include<QTreeWidgetItem>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
private slots:
void on_pushButton_clicked();
private:
Ui::Dialog *ui;
private:
void addRoot(QString name);
void add_Child(QTreeWidgetItem* parent, QString name);
};
#endif // DIALOG_H
//实现
#include "dialog.h"
#include "ui_dialog.h"
#include<QFont>
#include<QMessageBox>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
//创建三个顶级目录
addRoot("Root Level One");
addRoot("Root Level Two");
addRoot("Root Level Three");
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog:: addRoot(QString name)
{
QTreeWidgetItem *itm = new QTreeWidgetItem(ui->treeWidget);//传递父对象
itm->setText(0,name);
QFont serifFont("Times", 10, QFont::Bold);
itm->setFont(0, serifFont);
itm->setWhatsThis(0, "Root Level Tree");
ui->treeWidget->addTopLevelItem(itm);//把item添加为顶层
//添加6个child组件
add_Child(itm, "One Level");
add_Child(itm, "Two Level");
add_Child(itm, "Three Level");
add_Child(itm, "Four Level");
add_Child(itm, "Five Level");
add_Child(itm, "Six Level");
}
void Dialog:: add_Child(QTreeWidgetItem* parent, QString name)
{
//创建组件
QTreeWidgetItem *itm = new QTreeWidgetItem();
itm->setText(0,name);
//设置字体
QFont childFont;
childFont.setWeight(QFont::Black);
childFont.setStyle(QFont::StyleOblique);
childFont.setUnderline(true);
itm->setFont(0, childFont);
itm->setBackgroundColor(0,Qt::gray);
itm->setTextColor(0,Qt::red);
//把上面定义好的组件以child的形式添加到顶级组件中
parent->addChild(itm);
}
void Dialog::on_pushButton_clicked()
{
ui->treeWidget->currentItem()->setBackgroundColor(0, Qt::cyan);
}
//测试
#include <QtGui/QApplication>
#include "dialog.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
w.show();
return a.exec();
}
//结果