Qt - Centering a checkbox in a QTable

17,222

Solution 1

I usually use a layout and a container widget for this. It is an ugly solution, but it works:

QWidget * w = new QWidget();
QHBoxLayout *l = new QHBoxLayout();
l->setAlignment( Qt::AlignCenter );
l->addWidget( <add your checkbox here> );
w->setLayout( l );
ui->data_table->setCellWidget(rowCount,0, w);

So basically you will have:

Table Cell -> Widget -> Layout -> Checkbox

you'll have to consider it if you will need to access the checkbox through the table.

Solution 2

Two thumbs up for Barry Mavin! You don't even have to subclass.

one line...

pCheckBox->setStyleSheet("margin-left:50%; margin-right:50%;");

done!!

Solution 3

This is an old post but in fact there is a much easier and lighter way of achieving this, just subclass QCheckBox and set the stylesheet to

margin-left:50%;
margin-right:50%;

Solution 4

It works for me, but my checkbox is not completely displayed.

To have a complete view of the widget, remove margins in layout :

l->setContentsMargins(0,0,0,0);

Solution 5

As stated in similar question around Stack Overflow, it's currently an open BUG:

https://bugreports.qt-project.org/browse/QTBUG-5368

Share:
17,222
Mitch
Author by

Mitch

Updated on June 25, 2022

Comments

  • Mitch
    Mitch about 2 years

    In QtCreater I added a table to my project. in my code I am generating some data to output into the table. I want to add a QCheckbox into each row to allow the row to be selected. All the content of the table is aligned left, how do I make only these checkboxes in the first column of every row align to the center?

    I'm adding the QCheckbox using:

    ui->data_table->setCellWidget(rowCount,0, new QCheckBox);
    
  • Mitch
    Mitch over 11 years
    It seems like something that should be much easier then that. I was looking through docs for a long time trying to find a function or something that did what I wanted. But what you posted works perfectly, I would of never figured that out on my own though. Thanks!
  • Spencer
    Spencer over 6 years
    Im in PyQt4 and this only works when setting the initial value. That is, if I resize the column it does not continue to center the checkbox, it only centers it when it is first created.
  • Dark King
    Dark King over 4 years
    @SingerOfTheFall, how to get the checkstatus of the checkbox?
  • drescherjm
    drescherjm over 3 years
    For some reason margin-left:50%; margin-right:50%; is giving me off-center with respect to the column heading. Any ideas.
  • drescherjm
    drescherjm over 3 years
    I ended up using the first method which worked correctly without the offset.
  • jpo38
    jpo38 over 2 years
    Alignment is perfect here. It's not when using stylesheet proposed by other answers (where checkbox ends up shifted to the right by some pixels).