QTableView列的相对大小提示

3

我有一个使用自定义模型的QTableView。它包含了一列列的文本,每列文本的最大长度差别很大。

我知道可以实现自己的item delegate来提供列的大小提示,但是它似乎是以像素为单位指定的。我更愿意以与分辨率无关的方式完成此操作。

是否有一种方法可以按比例指定列的所需大小,类似于布局中水平拉伸因子的工作方式?

1个回答

5

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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接