QTableWidget: Prioritize horizontal space for a specific column?
-
I have a QTableWidget that has a column (#3) that needs more space than others. I want to resize all columns to their contents, and give priority to column #3. If column #3 pushes the table's width past what's available, I want column #3 to be truncated with '...' without a horizontal scrollBar.
The screenshot below is the simplest example of the behavior I'm chasing, but I've had to manually adjust the column widths. I want the table to do this automatically.
Note: These functions do not achieve what I'm aiming for. I want to stretch column 3 to take up the most horizontal space, but if it takes up too much space, then truncate it with elipses (aka "..."), and do not expand the table so that it has a horizontal scrollbar.
table->horizontalHeader()->setStretchLastSection(true); table->resizeColumnsToContents();
The following code shows examples of what I've tried on QTableWidget, but none have worked. Thank you to anyone who volunteers your time to help me with this.
#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(); }
-
@nagesh said in QTableWidget: Prioritize horizontal space for a specific column?:
table->horizontalScrollBar()->setEnabled(false);
table->resizeColumnsToContents();
QHeaderView *headerView = table->horizontalHeader();
headerView->setSectionResizeMode(2, QHeaderView::Stretch);Thank you