QTableView : cannot get its "natural" size in a grid layout

  • Hi all,

    I have a simple problem but cannot get it working. I have a small QTableView, alone inside a much bigger parent widget. I would like to display the table with its full size in the middle of its parent (centered).

    I do not want to expand the size of the table with ugly wide rows or columns or extra space after used lines and columns. I just want my 3 lines and 4 columns with their "natual" size, adjusted to their content. Right in the middle of the parent widget.

    I create a 3x3 grid layout in the parent widget. The table is in the center element of the layout and is surrounded by four spacers. I set a fixed size policy on the table. If I understand correctly the doc, this means that the table widget requests a size exactly identical to its size hint. Then, I expect the spacers to let the table expand as requested and place it in the center of the parent widget.

    However, what I get is a table widget which is either smaller (with a scroll bar) or bigger than the expected size. But the table is never displayed with its exact size. The logic behind the size of the surrounding spacers is unclear.

    What did I do wrong?
    Thanks in advance for your help.

    Qt 5.0.2 on Win7.

    Sample source code:

    #include <QtCore>
    #include <QtWidgets>

    int main(int argc, char *argv[])
    QApplication a(argc, argv);

    QDialog dialog;
    dialog.resize(500, 300);
    QTableWidget* tableWidget = new QTableWidget(&dialog);
    tableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem("Column 1"));
    tableWidget->setHorizontalHeaderItem(1, new QTableWidgetItem("Column 2"));
    tableWidget->setHorizontalHeaderItem(2, new QTableWidgetItem("Column 3"));
    tableWidget->setHorizontalHeaderItem(3, new QTableWidgetItem("Column 4"));
    tableWidget->setVerticalHeaderItem(0, new QTableWidgetItem("Line 1"));
    tableWidget->setVerticalHeaderItem(1, new QTableWidgetItem("Line 2"));
    tableWidget->setVerticalHeaderItem(2, new QTableWidgetItem("Line 3"));
    tableWidget->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
    QGridLayout* dialogLayout = new QGridLayout(&dialog);
    dialogLayout->addWidget(tableWidget, 1, 1);
    dialogLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding), 0, 1);
    dialogLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding), 2, 1);
    dialogLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding), 1, 0);
    dialogLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding), 1, 2);
    return a.exec&#40;&#41;;


    Project file:
    QT += core gui widgets
    TARGET = BoxTest
    TEMPLATE = app
    SOURCES += BoxTest.cpp

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.