【问题标题】:Relative size hints for QTableView columnsQTableView 列的相对大小提示
【发布时间】:2013-06-02 12:56:57
【问题描述】:

我有一个带有我自己的自定义模型的 QTableView。它包含一个文本列表,每个列的最大大小差异很大。

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

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

【问题讨论】:

    标签: qt qt5 qtableview


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-20
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-07
      • 2018-03-24
      相关资源
      最近更新 更多