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 不已经足以解决您的问题。
minimumSectionSize: int
了吗? - Surt