Increase space between text and checkbox in Qt
Pregunta
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:
Solución
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.
Otros consejos
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;
}