创建自定义按钮
Create Custom Button
我想创建一个没有任何样式的自定义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));
}
有两种解决方案:
- 子类QLabel发出click()信号并将图像加载到该子类
- 你可以把你的样式表设置为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中尝试:
- 你用你的png图片创建一个标签。
- 在标签的顶部放置一个样式表为"background:transparent;边界:没有;"
像一个按钮,看起来像一个图像;)
首先,添加一个资源文件,创建一个前缀并添加您需要的文件。在设计器中,右键单击按钮并更改样式表。
background: url(":filePath");
或者,你可以这样做,添加资源(是的,它会显示它是一个无效的样式表,但不要担心):然后通过在url之前添加关键字background来编辑代码,使其看起来像这样
background: url(":filePath");
其中file path是资源文件的路径,当您决定使用add resource选项时,会自动检测到该路径。
相关文章:
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- Qt自定义QPush按钮未显示在布局上
- 将自定义样式添加到 QTableview 中添加的按钮
- Qt - 为什么我无法在主窗口中为我的自定义按钮触发 mousePressEvent
- 将自定义按钮标题添加到消息框
- 在 QT 中创建自定义按钮
- 自定义光标未显示在自定义按钮上
- 在自定义控件中创建子按钮窗口后崩溃
- C++ MFC、带复选框的自定义网格、单选按钮
- 如何将自定义小部件添加为工具按钮的弹出菜单
- 有没有一种方法可以自定义C++中的按钮
- 自定义最小-最大关闭按钮实现
- Qt:在按钮点击上添加自定义新选项卡
- 创建自定义按钮
- 如何在自定义OleDB驱动程序中显示浏览按钮
- 在c++中是否有一种方法可以在不使用windows api的情况下制作带有按钮和滚动条的自定义gui ?
- c++自定义按钮图标
- 在自定义wxWidgets小部件中,两个相邻的按钮
- 如何获取标题栏窗口控件的 RECT(最大化、最小化、关闭按钮)?我尝试制作自定义颜色标题栏
- Qt复选框/工具按钮,带有自定义/不同的检查/未选中的图标