如何创建图标上显示文本的QPushButton

How to create a QPushButton with the text displayed over the icon?

本文关键字:显示 文本 QPushButton 图标 何创建 创建      更新时间:2023-10-16

我正在尝试在我的项目中创建一个QPushButton,以便文本显示在自定义按钮图像或图标的顶部。我尝试了以下方法:

imagePath = path;
QPixmap pixmap(imagePath);
QIcon ButtonIcon(pixmap);
button->setIcon(ButtonIcon);
button->setIconSize(pixmap.rect().size());
button->setGeometry(0,0,height,width);
button->setStyleSheet(
    "background-color: gray;"
    "border: 1px solid black;"
    "border-radius: "+QString::number(radius)+"px;"
    "color: lightGray; "
    "font-size: 25px;"
    );

当我尝试在此处使用setText时,它首先显示图标,右侧显示文本。我希望文本显示在图标顶部。

我还尝试了以下我在网上找到的方法:

imagePath = path;
button->setGeometry(0,0,height,width);
button->setStyleSheet("background-image: url(:/images/images/2adjacentTracksButton.png));"
                      "background-position: center center");

这个不接受我的 url 路径,因此没有在按钮上显示我需要的图像。

我该如何解决这个问题?

当涉及到操作按钮时,你可能想做自己的类,这将实现QAbstractButton。像这样:

class MyButton : public QAbstractButton
{
    Q_OBJECT
public:
    static MyButton* createButton(QIcon icon, QWidget *parent);
    ~MyButton();
    void setText(QString);
    void setIcon(eIcon);
    void setOrientation(Qt::Orientation);
protected : 
    MyButton(QWidget *parent);
    // here, you can reimplement event like mousePressEvent or paintEvent
private :
    QBoxLayout*  m_ButtonLayout;
    QLabel*      m_IconLabel;
    QIcon        m_Icon;
    QLabel*      m_TextLabel;
}

.cpp

MyButton::MyButton(QWidget *parent)
    : QAbstractButton(parent)
{    
    m_ButtonLayout = new QBoxLayout(QBoxLayout::LeftToRight, this);
    m_ButtonLayout->setAlignment(Qt::AlignCenter);
    m_ButtonLayout->setContentsMargins(0, 0, 0, 0);
    m_ButtonLayout->setSpacing(1);
    m_IconLabel = new QLabel(this);
    m_IconLabel->setAlignment(Qt::AlignCenter);
    m_ButtonLayout->addWidget(m_IconLabel);
    m_TextLabel = new QLabel(this);
    m_TextLabel->setAlignment(Qt::AlignCenter);
    m_ButtonLayout->addWidget(m_TextLabel);
    //m_TextLabel->hide();
}
MyButton* MyButton::createButton(QIcon icon, QWidget *parent)
{
    MyButton* pButton = new MyButton(parent);
    pButton->setIcon(icon);
    return pButton;
}
void MyButton::setText(QString text)
{
    m_TextLabel->setVisible(!text.isEmpty());
    m_TextLabel->setText(text);
    QAbstractButton::setText(text);
}
void MyButton::setIcon(QIcon icon)
{
    m_Icon = icon;
    m_IconLabel->setVisible(true);
}
void MyButton::setOrientation(Qt::Orientation orientation)
{
    if (orientation == Qt::Horizontal)
        m_ButtonLayout->setDirection(QBoxLayout::LeftToRight);
    else
        m_ButtonLayout->setDirection(QBoxLayout::TopToBottom);
}

现在,您可以通过调用静态方法创建带有图标的按钮:

MyButton* button = MyButton::createButton(myButtonIcon, this);

这只是我给你的一个基本例子,我不确定它会起作用(这是我前段时间做过的事情),但你可以试一试。希望有帮助!