Today I'm trying to configure a QTreeView
to fit my requirements. My view has basically three columns. The second and third column should be exactly 50 pixels wide no matter, what might be widgets size. The first column should occupy the remaining space.
If I enlarge my widget the first column should automatically occupy the need free space, whereas the second and third column should retain their given widths of 50 pixels.
This is what I tried so far:
main.cpp
#include <QApplication>
#include <QTreeView>
#include <QDebug>
#include <QStandardItemModel>
#include <QHeaderView>
#include "ColumnDelegate.h"
int main(int argc, char** args) {
QApplication app(argc, args);
auto widget = new QTreeView;
auto model = new QStandardItemModel;
model->insertRow(0, { new QStandardItem{ "Variable width" }, new QStandardItem{ "Fixed width 1" }, new QStandardItem{ "Fixed width 2" } });
model->insertRow(0, { new QStandardItem{ "Variable width" }, new QStandardItem{ "Fixed width 1" }, new QStandardItem{ "Fixed width 2" } });
widget->setModel(model);
widget->setItemDelegateForColumn(1, new ColumnDelegate);
widget->setItemDelegateForColumn(2, new ColumnDelegate);
auto header=widget->header();
header->setSectionResizeMode(QHeaderView::Fixed);
header->resizeSection(1, 50);
header->resizeSection(2, 50);
widget->show();
app.exec();
}
ColumnDelegate.h
#pragma once
#include <QStyledItemDelegate>
class ColumnDelegate : public QStyledItemDelegate {
Q_OBJECT
public:
virtual QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override
{
QSize ret= QStyledItemDelegate::sizeHint(option, index);
ret.setWidth(50);
return ret;
}
};
But after execution I got:
Does anyone knows how to implement my desired behavior with the least amount of work?