QHeaderView
个部分可能会偏离视图(右侧)。那就是我可以调整一个部分太大而其他部分将会消失到右边。
可以限制吗?例如设置标题的最大宽度。
我在桌面和标题上尝试setMaximumWidth
(实际上在真正的应用中,我只有标题表没有标准表),但它没有帮助。
UPD:
实际上我希望其他列缩小而不是走出可见区域,就像在MS Word中那样:
因此,如果没有像这样的行为的内置选项,那么我想我需要找到一个合适的信号来调整大小后调整大小,例如减少/增加下一列或上一列的大小...
答案 0 :(得分:2)
在Qt 5.12中设置
QHeaderView()->setCascadingSectionResizes(true);
和
QHeaderView()->setSectionResizeMode(c, QHeaderView::Stretch);
c = lastColumn;
答案 1 :(得分:0)
正如一些评论所说,您可以使用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);
}
}
}
}
有一些警告。我还没有在可重新排序的标题上对此进行测试,它讨论的是&#34; logicalIndices&#34;这可能意味着您需要使用sectionPosition
进行一些翻译。当视图变小时,它也不会做太多事情虽然它会在调整列大小后自行修复。你应该看看将ResizeMode设置为Stretch是否已经足以解决你的问题。