【问题标题】:QTreeView with fixed column widths具有固定列宽的 QTreeView
【发布时间】:2017-12-12 09:25:19
【问题描述】:

今天我正在尝试配置 QTreeView 以满足我的要求。我的观点基本上有三列。第二列和第三列应该正好是 50 像素宽,不管小部件的大小是多少。第一列应该占据剩余空间。

如果我放大我的小部件,第一列应该自动占据所需的可用空间,而第二和第三列应该保持它们给定的 50 像素宽度。

这是我迄今为止尝试过的:

ma​​in.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;
    }
};

但执行后我得到了:

有谁知道如何以最少的工作量实现我想要的行为?

【问题讨论】:

  • 你有一个列的拉伸模式,我想你可以通过QHeaderView将它设置为特定的列。如果您修复所有尺寸,除了您设置为拉伸的尺寸,它应该可以工作。
  • 谢谢。对于小费。你拯救了我的一天。

标签: c++ qt qtreeview qstyleditemdelegate qheaderview


【解决方案1】:

问题是调整大小模式统一应用于所有部分。您可以使用QHeaderView::setSectionResizeMode 的重载,它允许对每个部分的设置进行细粒度调整。在您的情况下,使用 resize modes: QHeaderView::Stretch 的组合用于扩展列,QHeaderView::Fixed 用于具有固定宽度的列。

此外,您必须禁用自动拉伸最后一部分的设置。使用QHeaderView::setStretchLastSection

例子:

header->setSectionResizeMode(0, QHeaderView::Stretch);
header->setSectionResizeMode(1, QHeaderView::Fixed);
header->setSectionResizeMode(2, QHeaderView::Fixed);
header->setStretchLastSection(false);

最后,QItemDelegate::sizeHint 对标有QHeaderView::Fixed 调整大小模式的部分没有任何影响。只需调用具有所需宽度的resizeSection 并忘记项目委托(除非您需要其他任何东西)。

【讨论】:

  • 感谢您的解决方案。刚刚在@ymoreau 的提示下找到它。
猜你喜欢
  • 1970-01-01
  • 2018-09-28
  • 1970-01-01
  • 1970-01-01
  • 2016-04-13
  • 2020-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多