Qt 學習筆記 TreeWidget 增刪改

2021-09-22 06:03:06 字數 3304 閱讀 1161

在窗體上放乙個treewidget控制項和四個pushbutton加乙個horizontal spacer

布局如圖

給樹新增元素節點的方法和實現

.**件

qtreewidgetitem *addtreeroot(qstring name,qstring desc);

qtreewidgetitem * addtreenode(qtreewidgetitem *parent,qstring name,qstring desc);

.cpp檔案

qtreewidgetitem *treeviewview::addtreeroot(qstring name,qstring desc)

qtreewidgetitem * treeviewview::addtreenode(qtreewidgetitem *parent,qstring name,qstring desc)

在構造方法裡新增元素設定樹的列數和標題的名稱

當然可以設定header不顯示,根據你的需求定

ui->tv_source->setcolumncount(2

); ui->tv_source->setheaderlabels(qstringlist()<

name

"<

description");

//ui->tv_source->setheaderhidden(true);

qtreewidgetitem * beijingitem = addtreeroot("

bejing

","city");

addtreenode(beijingitem,

"haidian

","haidian");

addtreenode(beijingitem,

"chaoyang

","chaoyang");

addtreenode(beijingitem,

"fengtai

","fengtai");

qtreewidgetitem * heibeiitem =addtreeroot("

hebei

","city");

addtreenode(heibeiitem,

"baoding

","baoding");

addtreenode(heibeiitem,

"shijiazhuang

","shijiazhuang

");

新增事件相對來說比較簡單

直接呼叫我的前邊寫的方法,因為treewidget一直是選中狀態就加了乙個

新增根節點的槽

void

treeviewview::on_btn_add_clicked()

else

}void

treeviewview::on_btn_addroot_clicked()

修改方法也很簡單

void

treeviewview::on_btn_modify_clicked()

for(int i=0;icolumncount();i++)

}

刪除槽就要考慮的多一點

要看它有沒有父節點

void

treeviewview::on_btn_del_clicked()

//如果沒有父節點就直接刪除

if(currentitem->parent()==q_nullptr)

else

}

看一下效果

完整**

.**件

#ifndef treeviewview_h

#define treeviewview_h#include

#include

#include

namespace

ui class treeviewview : public

qdialog

;#endif

//treeviewview_h

.cpp檔案

#include "

treeviewview.h

"#include

"ui_treeviewview.h

"#include

treeviewview::treeviewview(qwidget *parent) :

qdialog(parent),

ui(newui::treeviewview)

treeviewview::~treeviewview()

qtreewidgetitem *treeviewview::addtreeroot(qstring name,qstring desc)

qtreewidgetitem * treeviewview::addtreenode(qtreewidgetitem *parent,qstring name,qstring desc)

void treeviewview::on_tv_source_currentitemchanged(qtreewidgetitem *current, qtreewidgetitem *previous)

current->settextcolor(0

,qt::blue);

current->settextcolor(1

,qt::blue);

current->setbackground(0

,qt::red);

current->setbackground(1

,qt::red);

}void

treeviewview::on_btn_add_clicked()

else

}void

treeviewview::on_btn_addroot_clicked()

void

treeviewview::on_btn_del_clicked()

//如果沒有父節點就直接刪除

if(currentitem->parent()==q_nullptr)

else

}void

treeviewview::on_btn_modify_clicked()

for(int i=0;icolumncount();i++)

}

Qt學習筆記

1.參考資料 1 2 3 4 5 6 2.faq 2.1.qt creator 2.1.1.xp下用qt creator編譯自帶例子mdi sdi 當不勾選projects build settings build environment的 clear system environment 時,編譯...

QT學習筆記

1.在windows下配置好qt的環境變數以後,用cmd開始編譯,qmake project qmake hello.pro mingw32 make 結果出現錯誤 include 問題已經解決了,主要是 故而只需在.pro檔案中加入 greaterthan qt major version,4 q...

Qt 學習筆記

常用控制項對應類 窗體 qwidget 水平布局 qhboxlayout 豎直布局 qvboxlayout 網格布局 qgridlayout 按鈕 qpushbutton 標籤 靜態文字框 qlabel qlineedit label new qlabel tr find what lineedit...