创建树节点 (QTreeWidgetItem) 并添加到 QTreeWidget中:
// 创建子节点
QTreeWidgetItem *child1 = new QTreeWidgetItem(root);
child1->setText(0, "子节点1");
child1->setText(1, "子节点1的列2内容");
QTreeWidgetItem *child2 = new QTreeWidgetItem(root);
child2->setText(0, "子节点2");
child2->setText(1, "子节点2的列2内容");
// 添加节点到树
treeWidget.addTopLevelItem(root);
排序:
ui->treeWidget->setSortingEnabled(true);
ui->treeWidget->header()->setSortIndicatorShown(true);
ui->treeWidget->header()->setSortIndicator(0, Qt::AscendingOrder);
QtreeWidget加载数据库:
#include <QApplication>
#include <QMainWindow>
#include <QTreeWidget>
#include <QTreeWidgetItem>
#include <QtSql>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
// 创建主窗口和 QTreeWidget
QMainWindow mainWindow;
QTreeWidget treeWidget(&mainWindow);
treeWidget.setHeaderLabels({"列1", "列2"});
// 创建数据库连接
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("mydatabase.db"); // 替换为您的数据库文件名
// 打开数据库
if (!db.open()) {
qDebug() << "Database connection failed.";
return 1;
}
// 创建查询
QSqlQuery query;
query.exec("SELECT column1, column2 FROM mytable"); // 替换为您的表名和列名
// 遍历查询结果并添加到 QTreeWidget
while (query.next()) {
QString column1Value = query.value(0).toString();
QString column2Value = query.value(1).toString();
QTreeWidgetItem *item = new QTreeWidgetItem(&treeWidget);
item->setText(0, column1Value);
item->setText(1, column2Value);
}
treeWidget.show();
return app.exec();
}
标签:基本,QtreeWidget,setText,db,QTreeWidgetItem,treeWidget,使用,include,节点
From: https://blog.51cto.com/u_16246024/7427770