【发布时间】:2021-06-06 16:21:54
【问题描述】:
我有一个 QTableWidget,它有一列 (#3) 比其他列需要更多空间。我想将所有列的大小调整为它们的内容,并优先考虑第 3 列。如果第 3 列将表格的宽度推到可用范围之外,我希望第 3 列被截断为 '...' 而没有水平滚动条。
下面的屏幕截图是我所追求的行为的最简单示例,但我不得不手动调整列宽。我希望表格自动执行此操作。
以下代码显示了我在 QTableWidget 上尝试过的示例,但没有一个有效。我提供了内联 cmets,说明为什么以下方法不起作用:
table->horizontalHeader()->setStretchLastSection(true);
table->resizeColumnsToContents();
感谢所有愿意抽出时间帮助我的人。
#include <QApplication>
#include <QTableWidget>
#include <QStringList>
#include <QRect>
#include <QLayout>
#include <QDialog>
#include <QHeaderView>
#include <iostream>
int main( int argc, char* argv[] )
{
QApplication a(argc, argv);
QDialog* d = new QDialog();
d->setLayout( new QVBoxLayout() );
QTableWidget* table = new QTableWidget(1,4);
QStringList headers = {"1", "2", "3", "4"};
table->setHorizontalHeaderLabels(headers);
table->setItem(0, 0, new QTableWidgetItem("1"));
table->setItem(0, 1, new QTableWidgetItem("22222"));
table->setItem(0, 2, new QTableWidgetItem("33333333333333333333333333333"));
table->setItem(0, 3, new QTableWidgetItem("4"));
// Do nothing
//
// The table exceeds the dimensions of the dialog,
// and we get a horizontal scrollbar
// This also results in a horizontal scrollbar
//
// table->horizontalHeader()->setStretchLastSection(true);
// Resizing the columns introduces a horizontal scrollbar, and
// prevents the user from from changing column width
//
// table->resizeColumnsToContents();
// The table fits, but all columns are equally spaced.
// (We want column 3 to take up as much space as possible)
//
// table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
// Columns are resized to their contents,
// but column 3 is not truncated and we get a horizontal scrollBar
//
// table->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
d->layout()->addWidget( table );
d->show();
return a.exec();
}
【问题讨论】:
标签: c++ qt user-interface qtablewidget