其他分享
首页 > 其他分享> > QTreeWidget设置自动列宽

QTreeWidget设置自动列宽

作者:互联网

需要注意的是该功能是从Qt5.0开始才有的,5.0以前的版本用不了

代码

	// TreeWidget 自动列宽
    ui->treeWidget->header()->setSectionResizeMode(QHeaderView::ResizeToContents);

效果展示

在这里插入图片描述

完整代码 Widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QTreeWidget>
#include <QTreeView>
#include <QTreeWidgetItem>
#include <QAction>


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


    // TreeWidget 自动列宽
    ui->treeWidget->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
    // 测试

    QStringList headers;
    headers << "Name" << "Number" << "TEST_1";
    ui->treeWidget->setHeaderLabels(headers);
    //ui->treeWidget->adjustSize();

    QStringList rootTextList;
    rootTextList << "Root" << "0";
    QTreeWidgetItem *root = new QTreeWidgetItem(ui->treeWidget, rootTextList);

    new QTreeWidgetItem(root, QStringList() << QString("Leaf_______________________1") << "1");
    QTreeWidgetItem *leaf2 = new QTreeWidgetItem(root,
                                       QStringList() << QString("Leaf 2") << "2");
    leaf2->setCheckState(0, Qt::Checked);

    QList<QTreeWidgetItem *> rootList;
    rootList << root;
    ui->treeWidget->insertTopLevelItems(0, rootList);

    // QTreeWidgetItem 测试
    QTreeWidgetItem *cities = new QTreeWidgetItem(ui->treeWidget);
    cities->setText(0, tr("Cities"));
    QTreeWidgetItem *osloItem = new QTreeWidgetItem(cities);
    osloItem->setText(0, tr("Oslo"));
    osloItem->setText(1, tr("Yes"));

    QTreeWidget *treeWidget = new QTreeWidget();
    treeWidget->setColumnCount(1);
    QList<QTreeWidgetItem *> items;
    for (int i = 0; i < 10; ++i)
    {
        items.append(new QTreeWidgetItem(static_cast<QTreeWidget *>(nullptr), QStringList(QString("item: %1").arg(i))));
        items[i]->setBackground(0,Qt::Dense7Pattern);
    }
    ui->treeWidget->insertTopLevelItems(0, items);


    // 插入Action
    QAction *testAction = new QAction;
    testAction->setText(tr("A Action Here"));

    ui->treeWidget->addAction(testAction);

}

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


标签:Widget,QTreeWidget,QTreeWidgetItem,ui,treeWidget,new,自动,列宽,include
来源: https://blog.csdn.net/Fuel_Ming/article/details/120923921