Skip to content

Instantly share code, notes, and snippets.

@alexreinking
Created July 14, 2013 01:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexreinking/5992821 to your computer and use it in GitHub Desktop.
Save alexreinking/5992821 to your computer and use it in GitHub Desktop.
A complete example of a button that toggles between two icons in Qt 5.
#include "dialog.h"
Dialog::Dialog(QWidget *parent): QDialog(parent)
{
QVBoxLayout *mainLayout = new QVBoxLayout(this);
iconBtn = new QPushButton(QIcon(":/icon1.png"), "", this);
icon = 0;
mainLayout->addWidget(iconBtn);
connect(iconBtn, SIGNAL(clicked()), this, SLOT(toggleIcon()));
setLayout(mainLayout);
}
void Dialog::toggleIcon()
{
icon = (icon) ? 0 : 1;
QString fname = QString(":/icon%1.png").arg(icon+1);
iconBtn->setIcon(QIcon(fname)); //This will set the size automatically
}
Dialog::~Dialog()
{
delete iconBtn;
}
#ifndef DIALOG_H
#define DIALOG_H
#include <QtWidgets>
#include <QtGui>
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = 0);
~Dialog();
public slots:
void toggleIcon();
private:
QPushButton* iconBtn;
int icon;
};
#endif // DIALOG_H
#include "dialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
Q_INIT_RESOURCE(res); //Required for MSVC 2012.
QApplication a(argc, argv);
Dialog w;
w.show();
return a.exec();
}
<RCC>
<qresource prefix="/">
<file>icon1.png</file>
<file>icon2.png</file>
</qresource>
</RCC>
#-------------------------------------------------
#
# Project created by QtCreator 2013-07-13T19:42:21
#
#-------------------------------------------------
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = TestSO
TEMPLATE = app
SOURCES += main.cpp\
dialog.cpp
HEADERS += dialog.h
RESOURCES += \
res.qrc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment