添加Ui布局
头文件
#ifndef MAINWINDOW_H#define MAINWINDOW_H#include <QMainWindow>#include <QTreeWidgetItem>namespace Ui {class MainWindow;}class MainWindow : public QMainWindow{ Q_OBJECTpublic: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); QTreeWidgetItem * AddTreeRoot(QString name,QString desc); QTreeWidgetItem * AddTreeNode(QTreeWidgetItem *parent,QString name,QString desc);PRivate slots: void on_addRootButton_clicked(); void on_addButton_clicked(); void on_deleteButton_clicked(); void on_modifyButton_clicked();private: Ui::MainWindow *ui;};#endif // MAINWINDOW_H.cpp文件
#include "mainwindow.h"#include "ui_mainwindow.h"MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){ ui->setupUi(this); ui->treeWidget->setColumnCount(2); ui->treeWidget->setHeaderLabels(QStringList()<<"Name"<<"Description"); QTreeWidgetItem *beiJingItem = AddTreeRoot("BeiJing","City"); AddTreeNode(beiJingItem,"haiDian","HaiDian"); AddTreeNode(beiJingItem,"chaoYang","ChaoYang"); AddTreeNode(beiJingItem,"fengTai","FengTai"); QTreeWidgetItem *heBeiItem =AddTreeRoot("HeBei","City"); AddTreeNode(heBeiItem,"baoDing","BaoDing"); AddTreeNode(heBeiItem,"shiJiaZhuang","ShiJiaZhuang");}MainWindow::~MainWindow(){ delete ui;}QTreeWidgetItem *MainWindow::AddTreeRoot(QString name, QString desc){ QTreeWidgetItem *item=new QTreeWidgetItem(QStringList()<<name<<desc); ui->treeWidget->addTopLevelItem(item); return item;}QTreeWidgetItem *MainWindow::AddTreeNode(QTreeWidgetItem *parent, QString name, QString desc){ QTreeWidgetItem *item=new QTreeWidgetItem(QStringList()<<name<<desc); parent->addChild(item); return item;}void MainWindow::on_addRootButton_clicked(){ AddTreeRoot("new","new");}void MainWindow::on_addButton_clicked(){ QTreeWidgetItem *item= ui->treeWidget->currentItem(); if(item!=NULL) { AddTreeNode(item,"new","new"); } else { AddTreeRoot("new","new"); }}void MainWindow::on_deleteButton_clicked(){ QTreeWidgetItem *currentItem = ui->treeWidget->currentItem(); if(currentItem==NULL) { return; } //如果没有父节点就直接删除 if(currentItem->parent()==NULL) { delete ui->treeWidget->takeTopLevelItem(ui->treeWidget->currentIndex().row()); } else { //如果有父节点就要用父节点的takeChild删除节点 delete currentItem->parent()->takeChild(ui->treeWidget->currentIndex().row()); }}void MainWindow::on_modifyButton_clicked(){ QTreeWidgetItem * currentItem = ui->treeWidget->currentItem(); if(currentItem==NULL) { return; } for(int i=0;i<currentItem->columnCount();i++) { currentItem->setText(i,tr("Modify")+QString::number(i)); }}运行结果
新闻热点
疑难解答