QTableView大于其容器

时间:2018-11-08 13:54:24

标签: c++ qt qt5

我正在研究Qt应用。那里我有QMainWindow。在其中,我添加了QTableView。运行该应用程序时,我看到需要滚动以显示整个表格,并且在其下方还显示空白。 我希望主窗口水平调整大小以使用表所需的空间。我也希望它垂直调整大小以没有空间被使用。我该如何实现? 到目前为止,这是我的代码:

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();
}

1 个答案:

答案 0 :(得分:1)

将表的sizeAdjustPolicy设置为AdjustToContents视图,然后将水平和垂直方向的大小策略均设置为“固定”。

AdjustToContents可能会对视图中的动态内容造成轻微的性能损失,因为每次数据更改都可能会更改布局。

Qt Designer是一个非常实用的工具,可以快速找出布局问题; {table,list,tree} 小工具的行为与 views 完全一样(因为它们相同),并且可以在窗口小部件中快速填充虚拟数据Qt设计器。

相关问题