I have a QTableView with my own custom model. It contains a table of columns of text, each of which with wildly differing maximum sizes.
I know I can implement my own item delegate to provide a size hint for the columns but it looks like that's specified in pixels. I would rather do this in a resolution-independent way.
Is there a way to specify the desired sizes of the columns in ratios of each other, similarly to how horizontal stretch factors work in layouts?
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));
}
Usage:
StretchingHeader *header = new StretchingHeader(Qt::Horizontal, tableWidget);
header->setStretchFactors(StretchFactors() << 1 << 2 << 3);
header->setResizeMode(QHeaderView::Fixed);
header->setStretchLastSection(true);
tableWidget->setHorizontalHeader(header);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With