I have a QPushButton and on that I have a text and and icon. I want to make the text on the button to be bold and red. Looked at other forums, googled and lost my hope. Seems there is no way to do that if the button has an icon (of course if you don't creat a new icon wich is text+former icon). Is that the only way? Anyone has a better idea?
+4
A:
you make the subclass of "QPushbutton", then override the paint event, there you modify the text to your wish.
here it is,
class button : public QPushButton
{
Q_OBJECT
public:
button(QWidget *parent = 0)
{
}
~button()
{
}
void paintEvent(QPaintEvent *p2)
{
QPushButton::paintEvent(p2);
QPainter paint(this);
paint.save();
QFont sub(QApplication::font());
sub.setPointSize(sub.pointSize() + 7);
paint.setFont(sub);
paint.drawText(QPoint(300,300),"Hi");
paint.restore();
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
button b1;
b1.showMaximized();
return a.exec();
}
Shadow
2010-06-07 14:11:28
I have read that on the internet but have no idea what I should do. Could you add some details?
Narek
2010-06-07 14:23:26
Honestly I don't understand what is written here, but tried to instantiate from your class instead of QPushButton, but it does not make any change.
Narek
2010-06-07 15:03:47
I would avoid custom painting, as it will interfere with the style, button sizes etc.Narek: Did you try with Qt style sheets?
Frank
2010-06-07 15:04:39
Have tried {font: 75 10pt "MS Shell Dlg 2"; color: rgb(170, 0, 0)} , but bold does not work. (Size and color work!).
Narek
2010-06-07 15:11:28
@Narek, i have updated my code, i thought u only need how to subclass pushbutton, now i have also updated how to use this in main function.See you need to create the object of custom class button the paint event of button class handles the drawing,there you can draw as many strings as well as icons for the button at desired location
Shadow
2010-06-08 04:38:14
subclassing and custom drawing is overkill to this, nothing that can't be done through stylesheets
Harald Scheirich
2010-06-09 01:41:58
This is overkill for styling the text but it's a very good starting point when the whole button needs to be styled. Thanks!
jjrv
2010-10-02 14:20:23
+1
A:
You really don't need to subclass to change the formatting of your button, rather use stylesheets e.g.
QPushButton {
font-size: 18pt;
font-weight: bold;
color: #ff0000;
}
Applying this to the button that you want to change will make the buttons text 18pt, bold and red. You can apply via widget->setStyleSheet()
Applying this to a widget in the hierarchy above will style all the buttons underneath, the QT stylesheet mechanism is very flexible and fairly well documented.
You can set stylesheets in the designer too, this will style the widget that you are editing immediately
Harald Scheirich
2010-06-09 01:39:58