QTableWidget, centering cellWidgets
Asked Answered
I

2

7

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?

Impressive answered 26/9, 2017 at 19:43 Comment(0)
A
12

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/

Alithia answered 26/9, 2017 at 19:46 Comment(1)
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.Metaphysical
B
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.

Brigham answered 8/11, 2019 at 13:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.