创建自定义按钮

Create Custom Button

本文关键字:按钮 自定义 创建      更新时间:2023-10-16

我想创建一个没有任何样式的自定义pushButton,它只是显示一个。png图像。

我已经尝试创建一个pushButton与setIcon方法,但这使用pushButton银色样式,我只是想显示图像,并有它是一个按钮。

也,我尝试使用QAction

newAct = new QAction(QIcon(":/new/prefix1/images/appbar.close.png"),

但是如果没有工具栏,这不会显示任何内容。

有什么办法让它工作吗?

也许这段代码对您有所帮助。创建一个QPushButton,为它设置一个图标,并使用以下代码:

YourQPushButton->setFlat(true);

更新:

MyPushButton.h:

#ifndef MYPUSHBUTTON_H
#define MYPUSHBUTTON_H
#include <QLabel>
class MyPushButton : public QLabel
{
    Q_OBJECT
public:
    explicit MyPushButton(QWidget *parent = 0);
signals:
    void clicked();
protected:
    void mouseReleaseEvent(QMouseEvent *ev);
};
#endif // MYPUSHBUTTON_H

MyPushButton.cpp

void MyPushButton::mouseReleaseEvent(QMouseEvent *ev)
{
    emit clicked();
}

如何使用:

MyPushButton btn;
btn.setPixmap(QPixmap(":/rm.png"));
QObject::connect(&btn, SIGNAL(clicked()), qApp, SLOT(quit()));
btn.show();

您甚至可以将此函数添加到MyPushButton类中以提高效率:)

void MyPushButton::setIcon(QPixmap px, int w, int h)
{
    setPixmap(px.scaled(w, h));
}

有两种解决方案:

  1. 子类QLabel发出click()信号并将图像加载到该子类
  2. 你可以把你的样式表设置为QPushButton的东西,像这样

如果你想创建QLabel的子类,这里有一个类:

头qspoilerlabel.h:

#ifndef QSPOILERLABEL_H
#define QSPOILERLABEL_H
#include <QLabel>
#include <QEvent>
class QSpoilerLabel : public QLabel
{
    Q_OBJECT
public:
QSpoilerLabel( const QString & text, QWidget * parent = 0 );
QSpoilerLabel(){}
signals:
    void clicked();
public slots:
    void slotClicked();
protected:
    void mouseReleaseEvent ( QMouseEvent * event );
};
#endif // QSPOILERLABEL_H
源qspoilerlabel.cpp:

#include "qspoilerlabel.h"
QSpoilerLabel::QSpoilerLabel( const QString & text, QWidget * parent )
:QLabel(parent)
{
    connect( this, SIGNAL( clicked() ), this, SLOT( slotClicked() ) );    
}
void QSpoilerLabel::slotClicked()
{
//qDebug()<<"Clicked";
}
void QSpoilerLabel::mouseReleaseEvent ( QMouseEvent * event )
{
    emit clicked();
}

您可以使用setPixmap方法加载图像到标签。它看起来像这样:

label->setPixmap((QPixmap::fromImage(QImage(":/new/prefix1/images/appbar.close.png"));

您可以在QtCreator中尝试:

  1. 你用你的png图片创建一个标签。
  2. 在标签的顶部放置一个样式表为"background:transparent;边界:没有;"

像一个按钮,看起来像一个图像;)

首先,添加一个资源文件,创建一个前缀并添加您需要的文件。在设计器中,右键单击按钮并更改样式表。

    background: url(":filePath");

或者,你可以这样做,添加资源(是的,它会显示它是一个无效的样式表,但不要担心):然后通过在url之前添加关键字background来编辑代码,使其看起来像这样

    background: url(":filePath");

其中file path是资源文件的路径,当您决定使用add resource选项时,会自动检测到该路径。