6

Is there a way to place QCheckBox as a cell widget of QTableWidget in the center of a cell, not at the left side, without additional QWidget and adding the checkbox to it's layout?

2 Answers2

11

Use setCellWidget to add QCheckBox to table:

QWidget *checkBoxWidget = new QWidget(); //create QWidget
QCheckBox *checkBox = new QCheckBox();   //create QCheckBox
QHBoxLayout *layoutCheckBox = new QHBoxLayout(checkBoxWidget); //create QHBoxLayout 
layoutCheckBox->addWidget(checkBox);     //add QCheckBox to layout
layoutCheckBox->setAlignment(Qt::AlignCenter); //set Alignment layout
layoutCheckBox->setContentsMargins(0,0,0,0);

ui->tableWidget->setCellWidget(0,0, checkBoxWidget);

screenshot

Also use these line to resize to contents:

ui->tableWidget->resizeRowsToContents();
ui->tableWidget->resizeColumnsToContents();

setCellWidget: Sets the given widget to be displayed in the cell in the given row and column, passing the ownership of the widget to the table.

Reference: https://evileg.com/en/post/79/

Farhad
  • 4,119
  • 8
  • 43
  • 66
  • This works. However, it does not address the OP of aligning the `QCheckBox` in the table cell *without* using an additional `QWidget` as the parent of the `QCheckBox`. I have not found anything better, though. – Mike Finch Jul 14 '23 at 23:31
2

I have a simple solution without any additional layout if you want to use ui->tableWidget->resizeColumnsToContents():

Use checkBox->setStyleSheet( "text-align: center; margin-left:50%; margin-right:50%;" );

AFTER this, call ui->tableWidget->resizeColumnsToContents().

If the column is resized after this (eg. the table gets resized by the layout), you may have to call ui->tableWidget->resizeColumnsToContents() again.

It the widget is placed before the resulting column width is known, it retains its (wrong) position. Using resizeColumnsToContents() repositions it.

Anton F.
  • 466
  • 4
  • 8