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?
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);
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With