1

The followin code creates a QTableWidget with some content.

void MainWindow::on_pushButton_clicked()
{
    m_tbl = new QTableWidget;
    qDebug() << m_tbl->sizeHint(); // output "QSize(256, 192)"
    qDebug() << m_tbl->sizePolicy(); 
    /* above line outputs "QSizePolicy(horizontalPolicy = QSizePolicy::Policy(Expanding), verticalPolicy = QSizePolicy::Policy(Expanding))" */
    m_tbl->setRowCount(4);
    m_tbl->setColumnCount(2);
    m_tbl->horizontalHeader()->setVisible(false);
    m_tbl->verticalHeader()->setVisible(false);
    m_tbl->setItem(0,0,new QTableWidgetItem(QString("0,0")));
    m_tbl->setItem(0,1,new QTableWidgetItem(QString("0,1")));
    m_tbl->setItem(1,0,new QTableWidgetItem(QString("1,0")));
    m_tbl->setItem(1,1,new QTableWidgetItem(QString("1,1")));
    m_tbl->setItem(2,0,new QTableWidgetItem(QString("2,0")));
    m_tbl->setItem(2,1,new QTableWidgetItem(QString("2,1")));
    m_tbl->setItem(3,0,new QTableWidgetItem(QString("3,0")));
    m_tbl->setItem(3,1,new QTableWidgetItem(QString("3,1")));
    m_tbl->adjustSize(); // not making any difference
    m_tbl->show();
}

The problem is the window size is larger than the content - please see the image below. How could one let the window adjust its size according to its content in this case?

Window size is larger than its content

Thanks in advance.

sofname
  • 429
  • 1
  • 5
  • 20
  • [`adjustSize()`](https://doc.qt.io/qt-5/qwidget.html#adjustSize) takes size hint and policy into account. Since your size hint is valid, it will use the size hint. – Minh Nov 30 '20 at 06:44
  • 1
    This question has been asked many times before. Basically the solution is to calculate the width and height yourself, from the columns and rows ort he headers. https://stackoverflow.com/questions/8766633/how-to-determine-the-correct-size-of-a-qtablewidget – Minh Nov 30 '20 at 07:11
  • Check Zbyněk Winkler's answer in that post – Minh Nov 30 '20 at 07:15
  • 1
    @Ngoc Minh Nguyen Thanks for the information. For my case, I just needed the "length" part in the answer you pointed out, since my vertical/horizontal headers are hidden. – sofname Nov 30 '20 at 18:53

0 Answers0