Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QTableWidget, centering cellWidgets

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?

like image 489
Niall Cowperthwaite Avatar asked Sep 26 '17 19:09

Niall Cowperthwaite


2 Answers

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/

like image 123
Farhad Avatar answered Nov 08 '22 22:11

Farhad


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.

like image 37
Anton F. Avatar answered Nov 08 '22 21:11

Anton F.