How to resize columns in QTreeWidget to the minimum space required

后端 未结 2 1198
不思量自难忘°
不思量自难忘° 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.

提交回复
热议问题