Qt工作笔记-QTreeWidget求总结点数以及此树中最多孩子的个数(非递归)

话不多说,运行截图如下:

Qt工作笔记-QTreeWidget求总结点数以及此树中最多孩子的个数(非递归)_第1张图片


代码如下:

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include 
#include 
#include 

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

public slots:
    void pressBtn();

private:
    Ui::Widget *ui;
};

#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"


Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    QStringList header;
    header.append(tr("第一列"));
    header.append(tr("第二列"));
    header.append(tr("第三列"));

    ui->treeWidget->setHeaderLabels(header);

    QTreeWidgetItem *topItem1=new QTreeWidgetItem();
    topItem1->setText(0,tr("第一个头结点"));
    ui->treeWidget->addTopLevelItem(topItem1);

    QTreeWidgetItem *topItem2=new QTreeWidgetItem();
    topItem2->setText(0,tr("第二个头结点"));
    ui->treeWidget->addTopLevelItem(topItem2);

    ui->treeWidget->setColumnWidth(0,150);

    for(int i=1;i<=5;i++){
        QTreeWidgetItem *newItem=new QTreeWidgetItem();
        newItem->setText(0,tr("第")+QString::number(i)+"个子结点");
        topItem1->addChild(newItem);
    }

    ui->treeWidget->expandItem(topItem1);

    connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(pressBtn()));


}

void Widget::pressBtn(){
    QTreeWidgetItemIterator it(ui->treeWidget);

    int CountNum=0;      //注意int的范围
    int MaxNodeNum=0;   //注意int的范围
    MaxNodeNum=(*it)->childCount();
    while (*it) {
        CountNum++;
        if((*it)->childCount()>MaxNodeNum)
            MaxNodeNum=(*it)->childCount();
        it++;
    }

    ui->label_3->setText(QString::number(CountNum)+tr("个"));
    ui->label_4->setText(QString::number(MaxNodeNum)+tr("个"));
}

Widget::~Widget()
{
    delete ui;
}

main.cpp

#include "widget.h"
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

你可能感兴趣的:(C/C++,Qt,工作笔记)