Important: Please read the Qt Code of Conduct -

QTreeView in QTreeWidgetItem

  • Hi, guys!

    I have QTreeWidget with QTreeWidgetItems.
    QTreeWidgetItem should contain QTreeView.

    It work, but i need to resize QTreeView automaticaly by content.
    tree->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents); // do not work

    void MainWindow::addTreeView()
        QFileSystemModel *model = new QFileSystemModel();
        QTreeView *tree = new QTreeView();
        // ??
        tree->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents);   // not work
        tree->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
        QTreeWidgetItem *item = new QTreeWidgetItem(ui->treeWidget);
        ui->treeWidget->setItemWidget(item, 0, tree);
        // ??
        ui->treeWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    MainWindow::MainWindow(QWidget *parent) :
        ui(new Ui::MainWindow)

    How it can be implemented?


  • Lifetime Qt Champion

    @Craetor said in QTreeView in QTreeWidgetItem:

    QTreeWidgetItem should contain QTreeView.

    I don't understand this: do you mean an item in your tree should contain another tree?!

  • @jsulm, yes, on screenshot you can see tree QTreeWidget with QTreeWidgetItem which the contain QTreeView.
    But QTreeView can't execute setSizeAdjustPolicy - AdjustToContents.

  • This can't be solved with a single QTreeWidget and a clever model instead? I'm surprised you got this to work.

  • @qwasder85,
    how it can be solved?

  • I fixed this issue.

    1. QTreeView return correct sizeHint for AdjustToContents.
    2. I implemented QStyledItemDelegate for sending sizeHint to QTreeWidgetItem from the QTreeView and force call QTreeWidget updateGeometries.
    3. Child class of QTreeView call SetData(0, Qt::SizeHintRole, sizeHint()) for QTreeWidgetItem on expanded and collapsed

    it work fine, may be it very strange way, but i don't known another)

    QSize CSResizeDelegate::sizeHint(const QStyleOptionViewItem&, const QModelIndex& index) const
        CSResizableTreeWidgetItem *item = static_cast<CSResizableTreeWidgetItem*>(index.internalPointer());
            ((CSResizableTreeWidget*)item->treeWidget())->updateGeometriesPublic(); // force call QTreeWidget::updateGeometries
        return item->getTree()->sizeHint(); // return QTreeView::sizeHint

    alt text

  • @Craetor
    Just to say: I don't really know what you're trying to achieve here. You say you're nesting QTreeViews within QTreeWidget, why do you not just use 2 separate QTreeWidget/Views? But I may not be understanding...

  • @JonB
    This code is a small example to find solution.
    In my real project i need to show tree with different items and nested trees.