문제

If you set a fixed checkbox size, the text will be aligned to the checkbox itself. With the standard layout direction, the text will start right after the box, and with right-to-left layout it will end right before the box, just like this (the border is just the widget's border to indicate the widget/s real size, don't be confused):

Is there a way to align the text to the other side to achieve this:

enter image description here

도움이 되었습니까?

해결책

As you mentioned you have a fixed size QCheckBox. So easily without subclassing you can get to your desire QCheckBox using style sheets. But unfortunately text-align property just works for QPushButton and QProgressBar. But the alternate stylesheet that you can use is :

QCheckBox{
spacing:100px;
}

With RightToLeft direction for your QCheckBox and this style sheet your checkbox is ready! :) . Change spacing according to your application.
Hope this helps.
here is my output

다른 팁

You can try inherit from QCheckBox and draw what you want. Look to this example custom push_button (add shadow to the text on the button).

#include "CustomButton.h"
#include <QStylePainter>
#include <QStyleOptionButton>
#include <QMenu>


CustomButton::CustomButton(QWidget *parent):
    QPushButton(parent)
{
}

void CustomButton::paintEvent(QPaintEvent *event)
{
    QStylePainter p(this);
    QFontMetrics font = this->fontMetrics();

    QRect textRect = font.boundingRect(text());
    int x = rect().center().x()-textRect.center().x();
    int y = rect().center().y()-textRect.center().y();
    ++y;
    p.drawControl(QStyle::CE_PushButton, getStyleOption()); //draw button with stylesheet
    QStyleOptionButton opt = getStyleOption();
    opt.text = text();
    QPen tempPen = p.pen();
    p.setPen(Qt::white);
    p.drawText(x, y,  text()); //draw text shadow on the button
    p.setPen(tempPen);
    p.drawControl(QStyle::CE_PushButtonLabel, opt); //draw text with stylesheet 
    //QPushButton::paintEvent(event);
}

QStyleOptionButton CustomButton::getStyleOption() const
{
    QStyleOptionButton opt;
    opt.initFrom(this);
    opt.features = QStyleOptionButton::None;
    if (isFlat())
        opt.features |= QStyleOptionButton::Flat;
    if (menu())
        opt.features |= QStyleOptionButton::HasMenu;
    if (autoDefault() || isDefault())
        opt.features |= QStyleOptionButton::AutoDefaultButton;
    if (isDefault())
        opt.features |= QStyleOptionButton::DefaultButton;
    if (isDown() || (menu() && menu()->isVisible()))
        opt.state |= QStyle::State_Sunken;
    if (isChecked())
        opt.state |= QStyle::State_On;
    if (!isFlat() && !isDown())
        opt.state |= QStyle::State_Raised;
    //opt.text = text();
    opt.icon = icon();
    opt.iconSize = iconSize();

    return opt;
}

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top