qt - QTableView 列的相对大小提示

标签 qt qt5 qtableview

我有一个带有我自己的自定义模型的 QTableView。它包含一个文本列表,每个文本列的最大大小都大不相同。

我知道我可以实现自己的项目委托(delegate)来为列提供大小提示,但它看起来是以像素为单位指定的。我宁愿以独立于分辨率的方式来做这件事。

有没有办法按照彼此的比例指定列的所需大小,类似于水平拉伸(stretch)因子在布局中的工作方式?

最佳答案

StretchingHeader.h:

#ifndef STRETCHINGHEADER_H
#define STRETCHINGHEADER_H

#include <QHeaderView>

class StretchFactors : public QList < int >
{
public:
    StretchFactors() :
        QList()
    {}
    StretchFactors(const StretchFactors &other) :
        QList(other)
    {}
    StretchFactors(const QList < int > &other) :
        QList(other)
    {}

    int factor(int section)
    {
        if (section < count())
            return at(section);
        return 1;
    }
};

class StretchingHeader : public QHeaderView
{
    Q_OBJECT
public:
    explicit StretchingHeader(Qt::Orientation orientation, QWidget *parent = 0);

    void setStretchFactors(const StretchFactors &stretchFactors);

protected:
    void resizeEvent(QResizeEvent *event);
    void showEvent(QShowEvent *event);

    void stretch();

protected:
    StretchFactors mStretchFactors;
};

#endif // STRETCHINGHEADER_H

StretchingHeader.cpp:

#include "StretchingHeader.h"

StretchingHeader::StretchingHeader(Qt::Orientation orientation, QWidget *parent) :
    QHeaderView(orientation, parent)
{
}

void StretchingHeader::setStretchFactors(const StretchFactors &stretchFactors)
{
    mStretchFactors = stretchFactors;
}

void StretchingHeader::resizeEvent(QResizeEvent *event)
{
    QHeaderView::resizeEvent(event);
    if (!mStretchFactors.isEmpty())
        stretch();
}

void StretchingHeader::showEvent(QShowEvent *event)
{
    QHeaderView::showEvent(event);
    if (!mStretchFactors.isEmpty())
        stretch();
}

void StretchingHeader::stretch()
{
    int totalStretch = 0;
    for (int i = 0; i < count(); ++i)
        totalStretch += mStretchFactors.factor(i);
    int oneWidth = width() / totalStretch;
    for (int i = 0; i < count(); ++i)
        resizeSection(i, oneWidth * mStretchFactors.factor(i));
}

用法:

StretchingHeader *header = new StretchingHeader(Qt::Horizontal, tableWidget);
header->setStretchFactors(StretchFactors() << 1 << 2 << 3);
header->setResizeMode(QHeaderView::Fixed);
header->setStretchLastSection(true);
tableWidget->setHorizontalHeader(header);

关于qt - QTableView 列的相对大小提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16882973/

相关文章:

c++ - Qt creator,错误信息

c++ - QListWidget 不允许图标大小大于 200

c++ - 如何从选定行(QTableView)中获取单元格值?

python - 访问 QTableView 中的特定元素/项目?

qt - QT 未满足的依赖关系

c++ - 如何从 Qt 应用程序驱动 excel 窗口

c++ - 不调用 mouseReleaseEvent

qt - 如何在 ListView 的项目之间设置自定义分隔符

c++ - 如何正确恢复由 windows 7/vista aero snap 调整大小的小部件

c++ - Qt:显示用户/客户列表并在单击时显示个人资料