繁体   English   中英

如何限制QHeaderView大小(调整部分大小时)?

[英]How to limit QHeaderView size (when resizing sections)?

调整大小时, QHeaderView部分可能会偏离视图(右侧)。 那就是我可以调整一个部分太大而其他部分将会消失到右边。

可以限制吗? 例如设置标题的最大宽度。

我在表和标题上尝试了setMaximumWidth (实际上在真正的应用程序中我只有没有标准表的标题)但它没有帮助。

在此输入图像描述

UPD:

实际上我希望其他列缩小而不是走出可见区域,就像在MS Word中一样:

在此输入图像描述

因此,如果没有像这样的行为的内置选项,那么我想我需要在调整大小后找到合适的信号来调整大小,例如减少/增加下一列或上一列的大小......

在Qt 5.12中设置

QHeaderView()->setCascadingSectionResizes(true);

QHeaderView()->setSectionResizeMode(c, QHeaderView::Stretch);
c = lastColumn;

好吧,正如一些评论所说,您可以使用来自QHeaderView信号来监听更改,然后使用resizeSection()更改它们。 下面我写了一个AutoResizer来执行你想要的调整大小。

AutoResizer.hpp

#ifndef AUTORESIZER_HPP
#define AUTORESIZER_HPP

#include <QObject>

class QHeaderView;

class AutoResizer : public QObject
{
    Q_OBJECT

    QHeaderView *m_header;
public:
    AutoResizer(QHeaderView *parent = 0);

private slots:
    // Listen to resized sections
    void sectionResized(int logicalIndex, int oldSize, int newSize);
};

#endif // AUTORESIZER_HPP

AutoResizer.cpp

#include "AutoResizer.hpp"

#include <QHeaderView>

AutoResizer::AutoResizer(QHeaderView *parent) : QObject(parent), m_header(parent)
{
    // Connect ourselves to the section resize signal
    connect(m_header,SIGNAL(sectionResized(int,int,int)),SLOT(sectionResized(int,int,int)));

    // Enable last column to stretch as we don't do that ourselves
    m_header->setStretchLastSection(true);
}

void AutoResizer::sectionResized(int logicalIndex, int oldSize, int newSize)
{
    // Do some bookkeeping
    int count = m_header->model()->columnCount(QModelIndex());
    int length = m_header->width(); // The width of the headerview widget
    int sum = m_header->length(); // The total length of all sections combined

    // Check whether there is a discrepancy
    if(sum != length) {
        // Check if it's not the last header
        if(logicalIndex < count) {
            // Take the next header size (the one right to the resize handle)
            int next_header_size = m_header->sectionSize(logicalIndex+1);
            // If it can shrink
            if(next_header_size > (sum - length)) {
                // shrink it
                m_header->resizeSection(logicalIndex+1, next_header_size - (sum - length));
            } else {
                // The next header can't shrink, block the resize by setting the old size again
                m_header->resizeSection(logicalIndex, oldSize);
            }
        }
    }
}

有一些警告。 我没有在可重新排序的标题上测试它,它谈到了“logicalIndices”,这可能意味着你需要使用sectionPosition一些翻译。 当视图变小时,它也不会做太多,尽管一旦调整列的大小,它将自行修复。 您应该查看将ResizeMode设置为Stretch是否已经足以解决您的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM