Search code examples
c++qtqt5qtwidgets

How to set max width for QTreeView resizeColumnToContents?


I'm using QTreeView::resizeColumnToContents(int column)

but if even after that I'm doing something alike

  if (t->columnWidth(0) > 10) {
    t->setColumnWidth(0, 10);
  }

it doesn't work, how can I set max width there?


Solution

  • It would be worth checking whether your if-statement gets executed at all or if the pointer t is able to modify the object.

    I've modified the Qt demo "simpletreemodel" to use this function and it works fine. I'm using Qt 5.7.0 for this.

    int main(int argc, char *argv[])
    {
        Q_INIT_RESOURCE(simpletreemodel);
    
        QApplication app(argc, argv);
    
        QFile file(":/default.txt");
        file.open(QIODevice::ReadOnly);
    
        TreeModel model(file.readAll());
        file.close();
    
        QTreeView view;
        view.setModel(&model);
        view.setWindowTitle(QObject::tr("Simple Tree Model"));
    
        std::cout<< view.columnWidth(0) <<std::endl;
        if (view.columnWidth(0) <= 100)
        {
            std::cout<< "resizing column width >> ";
            view.resizeColumnToContents(0);
            std::cout<< view.columnWidth(0) <<std::endl;
    
            if (view.columnWidth(0) > 250)
            {
                std::cout<< "oops! This is too much.. (max width = 250)" <<std::endl;
                view.setColumnWidth(0,250);
            }
        }
        std::cout<< view.columnWidth(0) <<std::endl;
    
        view.show();
        return app.exec();
    }
    

    The output from the above is:

    100
    resizing column width >> 269
    oops! This is too much.. (max width = 250)
    250
    

    Some more information on this would be nice.