How to resize columns in QTreeWidget to the minimum space required

后端 未结 2 1175
不思量自难忘°
不思量自难忘° 2021-01-04 09:12

I am a student programmer and I am using Qt to build a GUI interface for work. I have a QTreeWidget that has a total of 8 Columns. The input that needs to be en

相关标签:
2条回答
  • 2021-01-04 09:49

    This minimal example works for me:

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    
        QVBoxLayout *layout = new QVBoxLayout(centralWidget());
        QTreeWidget *tree = new QTreeWidget(this);
        layout->addWidget(tree);
    
        tree->setColumnCount(3);
    
        QStringList first, second, third;
        first  << "xxxxxxxxx"      << "xxxxxxxxxxxxx"     << "xxxxxxxx";
        second << "xxxxx"          << "xxxxxxxxxxxxxxxxx" << "xxxxx";
        third  << "xxxxxxxxxxxxxx" << "xxxxxxxxxx"        << "xxxxxxxx";
    
        tree->insertTopLevelItem(0, new QTreeWidgetItem(first));
        tree->insertTopLevelItem(0, new QTreeWidgetItem(second));
        tree->insertTopLevelItem(0, new QTreeWidgetItem(third));
    
        for(int i = 0; i < 3; i++)
            tree->resizeColumnToContents(i);
    }
    

    All you need to do is call the resizeColumnToContents() method once for every column after you populate the view. Let me know if the problem persists.

    0 讨论(0)
  • 2021-01-04 09:52

    The problem for me was that StretchLastSection was set to true and if this value is set to true, this property will override the resize mode set on the last section in the header.

    Solution:

    _treeWidget = new UIWidgetSceneTree();
    _treeWidget->header()->setStretchLastSection(false);
    _treeWidget->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
    
    0 讨论(0)
提交回复
热议问题