学习一下,据说QTreeWidget简单好用,不需要单独设置Model和View,更没有delegate。Signal和Slot应该可以正常使用(未验证,以后补充)。
#include <QtGui/QApplication> #include <QTreeWidget> #include <QDebug> // 定义结构体,只包括四个指针 typedef struct { char * sect_id, * title, * page_num; char * parent_id; } SectionInfo; // 注意1,靠内容(最后一项)来设置上下级关系 // 注意2,它们不是按顺序排列的 SectionInfo directory[] = { {"Chapter 1", "The Prehistory of C++", "19", ""}, {"Chapter 2", "C with Classes", "27", ""}, {"Section 1.1", "Simula and Distributed Systems", "19", "Chapter 1"}, {"Section 1.2", "C and Systems Programming", "22", "Chapter 1"}, {"Section 2.4", "Run-Time Efficiency", "32", "Chapter 2"}, {"Section 2.4.1", "Inlining", "33", "Section 2.4"}, }; int main(int argc, char *argv[]) { QApplication app(argc, argv); QTreeWidget * treeWidget = new QTreeWidget(); // 设置列数(赤裸裸简单规定多少列的情况不多见啊) treeWidget->setColumnCount(3); // 设置表头 QStringList headers; headers << "Section Number" << "Title" << "Page Number"; treeWidget->setHeaderLabels(headers); // 循环一共执行六次 for (int i=0; i<sizeof(directory)/sizeof(directory[0]); i++) { SectionInfo info = directory[i]; // 给C++结构体赋值,还挺巧妙的 QTreeWidgetItem * item=NULL; if (strcmp(info.parent_id, "")==0 ){ item = new QTreeWidgetItem(treeWidget); // 设置一行依附于整体 }else{ QString parent_id(info.parent_id); // 取得当前行父节点的文字,用于比较 QTreeWidgetItemIterator it (treeWidget); // 取得整体treeWidget的迭代子项,注意是一行一行迭代 // 直到i=4,才会进入while循环,0和1不会进入else,2和3第一次比较就不成立,所以不会进入while while ( (*it)->text(0) != parent_id) { // text(0)是QTreeWidgetItem的函数,即第零列的文字 qDebug() << i << " " << (*it)->text(0); ++it; } item = new QTreeWidgetItem( *it ); // 把最后一行空迭代子项变成一行,并把找到的节点设为父节点 good } // 有了item及可以设置内容了 if ( item) { item->setText(0, info.sect_id); item->setText(1, info.title ); item->setText(2, info.page_num); } } treeWidget->resize(400,200); treeWidget->show(); return app.exec(); }
参考:
http://book.51cto.com/art/201207/347905.htm
时间: 2024-11-08 09:12:38