QPushButton根据文本内容调整大小

时间:2025-04-27 07:11:17

Notes:

1、Qt中stylesheet设置的样式只有在widget显示之后才会生效,

2、If Qt Style Sheets are used on the same widget as functions that set the appearance of widgets, such as QWidget::setFont() or QTreeWidgetItem::setBackground(), style sheets will take precedence if the settings conflict.

#include <QApplication>
#include <QWidget>
#include <QPushButton>

int main(int argc, char *argv[])
{
    QWidget *p_w = new QWidget();
    QString txt = "AAAAAAAA";
    QPushButton *p_btn = new QPushButton(txt, p_w);
    QFont *p_font = new QFont("times", 20, QFont::Bold);
    QFontMetrics metrics(*p_font);

    p_btn->setFont(*p_font);
    //通过文本内容设置按钮大小,并在此基础上扩大2倍
    p_btn->setFixedSize((txt).size()*2);

    p_w->show();

    return ();
}

相关文章