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?
The problem is that the resize mode is applied to all the sections uniformly. You can use the overload of QHeaderView::setSectionResizeMode
that allows per-section settings to fine-grain tuning. In your case, using a combination of resize modes: QHeaderView::Stretch
for expanding columns and QHeaderView::Fixed
for those with fixed width.
Also, you have to disable the setting that automatically stretches the last section. Use QHeaderView::setStretchLastSection
.
Example:
header->setSectionResizeMode(0, QHeaderView::Stretch);
header->setSectionResizeMode(1, QHeaderView::Fixed);
header->setSectionResizeMode(2, QHeaderView::Fixed);
header->setStretchLastSection(false);
Finally, the QItemDelegate::sizeHint
doesn't have any effect over sections marked with a QHeaderView::Fixed
resize mode. Just call the resizeSection
with the desired width and forget about the item delegate (unless you need for anything else).
来源:https://stackoverflow.com/questions/47769122/qtreeview-with-fixed-column-widths