码迷,mamicode.com
首页 > 编程语言 > 详细

QTreeWidget的一个例子,C++语法和item迭代循环都比较巧妙

时间:2014-10-29 19:03:40      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   使用   for   sp   

学习一下,据说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

QTreeWidget的一个例子,C++语法和item迭代循环都比较巧妙

标签:style   blog   http   io   color   ar   使用   for   sp   

原文地址:http://www.cnblogs.com/findumars/p/4060175.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!