Qt - QPushButton text formatting

2019-02-13 14:57发布

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?

3条回答
仙女界的扛把子
2楼-- · 2019-02-13 15:38

You can subclass a QLabel and completely throw away all of its mouse events (so they reach the parent). Then crate a QPushButton, set a layout on it and in this layout insert a QLabel with formatted text. You get a button that contains QLabel and is clickable. (Any Qt Widget can have layout set, including ones that you never ever expected they can.)

查看更多
相关推荐>>
3楼-- · 2019-02-13 15:45

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

查看更多
该账号已被封号
4楼-- · 2019-02-13 15:48

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();
}
查看更多
登录 后发表回答