RuLoViC
RuLoViC

Reputation: 855

QTableView bigger than its container

I am working on Qt applicaction. There I have QMainWindow. Inside it I have added QTableView. When I run the application I see that I need to scroll to display the whole table and also blank space shows up below it. I would like main window to resize horizontally in order to use space needed by the table. Also I would like it to resize vertically to not having space unused. How could I achieve that? This is my code so far:

void MainWindow::initUi() {
   setWindowTitle(tr("Main Window"));
   QWidget* centralWidget = new QWidget(this);
   QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);
   QFormLayout *upperLayout = new QFormLayout;
   // Default layout appearance of QMacStyle
   upperLayout->setRowWrapPolicy(QFormLayout::DontWrapRows);
   upperLayout->setFieldGrowthPolicy(QFormLayout::FieldsStayAtSizeHint);
   upperLayout->setFormAlignment(Qt::AlignHCenter | Qt::AlignTop);
   upperLayout->setLabelAlignment(Qt::AlignLeft);

   QVBoxLayout *resultsLayout = new QVBoxLayout;
   QTableView* table = new QTableView(centralWidget);
   table->verticalHeader()->hide();
   QStandardItemModel* model= new QStandardItemModel(4, 4);
      for (int row = 0; row < 4; ++row) {
         for (int column = 0; column < 4; ++column) {
            QStandardItem *item = new QStandardItem(QString("row %0, column %1").arg(row).arg(column));
            model->setItem(row, column, item);
         }
      }

    table->setModel(model);
    QLabel* upperLabel = new QLabel(tr("Label:"), centralWidget);
    upperLabel->setAlignment(Qt::AlignLeft);
    resultLabel = new QLabel(tr("Result goes here"), centralWidget);
    mainLayout->addLayout(resultsLayout);
    resultsLayout->addLayout(upperLayout);
    resultsLayout->addWidget(table);
    upperLayout->addRow(upperLabel, resultLabel);
    centralWidget->setLayout(mainLayout);
    setCentralWidget(centralWidget);
    this->adjustSize();
}

Upvotes: 0

Views: 236

Answers (1)

dom0
dom0

Reputation: 7486

Set the sizeAdjustPolicy of the table to AdjustToContents view, then set the size policy to Fixed in both horizontal and vertical directions.

AdjustToContents might incur a slight performance penalty for dynamic contents in the view, since every data change may change the layout.

The Qt Designer is a really nifty tool to figure layout issues out quickly; the {table,list,tree} widgets behave exactly the same as the views do (because they're the same) and the widgets can be quickly filled with dummy data in Qt Designer.

Upvotes: 1

Related Questions