user4501385
user4501385

Reputation:

Align QCheckbox text and a QLabel underneath it

I have a checkbox with some text and I have a label underneath this checkbox. How can I align this label so it aligns with the text on the checkbox.

What I want:

[ ] insert_text
    some_text 

What I have:

[ ] insert_text
some_text

Upvotes: 2

Views: 594

Answers (2)

danpla
danpla

Reputation: 665

Use QStyle::pixelMetric() to get the sum of QStyle::PM_IndicatorWidth and QStyle::PM_CheckBoxLabelSpacing.

Then you can use it as a margin for QLabel, either with QBoxLayout::addSpacing() or QLayout::setContentsMargins() (for the latter, you will need QMargins::setLeft/Right() depending on the layout direction).

Upvotes: 0

eyllanesc
eyllanesc

Reputation: 243897

A possible solution is to add a padding to the left side of the QLabel of a suitable width, to calculate the width I have created a custom QCheckBox that returns the width of the indicator but to that amount you must add a couple of pixels that represent the space between the indicator and the text:

#include <QtWidgets>

class CheckBox: public QCheckBox{
public:
    using QCheckBox::QCheckBox;
    int width_of_indicator(){
        QStyleOptionButton opt;
        initStyleOption(&opt);
        return  style()->subElementRect(QStyle::SE_CheckBoxIndicator, &opt,this).width();
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget w;
    auto ch = new CheckBox("insert_text");
    auto label = new QLabel("some_text: Stack Overflow");
    label->setStyleSheet(QString("padding-left: %1px").arg(ch->width_of_indicator()+2));
    auto lay = new QVBoxLayout(&w);
    lay->addWidget(ch);
    lay->addWidget(label);
    w.show();
    return a.exec();
}

Upvotes: 3

Related Questions