Article source: blog.csdn.net/free_progra…

 #ifndef DIALOG_H
Copy the code
 #define DIALOG_H
Copy the code
Copy the code
 #include <QDialog> 
Copy the code
 #include<QTreeWidgetItem> 
Copy the code
Copy the code
namespace Ui {
Copy the code
class Dialog; 
Copy the code
 } 
Copy the code
Copy the code
class Dialog : public QDialog
Copy the code
 {
Copy the code
 Q_OBJECT
Copy the code
 
Copy the code
public: 
Copy the code
 explicit Dialog(QWidget *parent = 0); 
Copy the code
 ~Dialog(); 
Copy the code
 
Copy the code
private slots: 
Copy the code
 void on_pushButton_clicked(); 
Copy the code
Copy the code
private: 
Copy the code
 Ui::Dialog *ui; 
Copy the code
Copy the code
private: 
Copy the code
 void addRoot(QString name); 
Copy the code
 void add_Child(QTreeWidgetItem* parent, QString name); 
Copy the code
 }; 
Copy the code
Copy the code
 #endif // DIALOG_H
Copy the code
 
Copy the code
 
Copy the code
/ / implementationCopy the code
#include "dialog.h" #include "ui_dialog.h" #include<QFont> #include<QMessageBox> Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); // Create three top-level directories 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); Add_Child (ITM, "One Level"); 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* itm = new QTreeWidgetItem(); itm->setText(0,name); // Set the font 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); Parent ->addChild(itM); parent->addChild(itM); } void Dialog::on_pushButton_clicked() { ui->treeWidget->currentItem()->setBackgroundColor(0, Qt::cyan); }Copy the code
/ / testCopy the code
 
Copy the code
#include <QtGui/QApplication> #include "dialog.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); Dialog w; w.show(); return a.exec(); } / / resultsCopy the code

\