Reputation: 3121
I made a simple program to demonstrate my issues with attempting to use the QIcon swap() function. I am trying to swap the icons on two QPushButtons using this function, but it doesnt seem to be working.
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPushButton>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void swap_icons();
private:
Ui::MainWindow *ui;
QPushButton *buttons[2];
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
buttons[0] = new QPushButton(QString::number(0), this);
buttons[1] = new QPushButton(QString::number(1), this);
QPixmap pix(":/BP.PNG");
QIcon icon(pix);
buttons[0]->move(100,100);
buttons[0]->setIcon(icon);
buttons[0]->setIconSize(pix.size());
connect(buttons[0], SIGNAL(clicked()), this, SLOT(swap_icons()));
QPixmap pix2(":/BR.PNG");
QIcon icon2(pix2);
buttons[1]->setIcon(icon2);
buttons[1]->setIconSize(pix.size());
}
void MainWindow::swap_icons() {
buttons[0]->icon().swap(buttons[1]->icon());
}
MainWindow::~MainWindow()
{
delete ui;
}
When I push buttons[0], the icons do not swap. They remain the same.
Upvotes: 0
Views: 850
Reputation: 21220
You do not set the new icon. I think it should be like:
buttons[0]->setIcon(buttons[0]->icon().swap(buttons[1]->icon()));
However this will change only the first button's icon.
I would write it in more simple way, which is easier to read and understand:
QIcon tmp = buttons[0]->icon();
buttons[0]->setIcon(buttons[1]->icon());
buttons[1]->setIcon(tmp);
Upvotes: 1