Question

I would be very grateful if you could help me solve this :

I have a subclass of QPushButton called Square and what I want to do is to change the icon of one instance by clicking another instance of Square. I have a vector of vectors of pointers to squares called sqMatrix :

std::vector< std::vector<Square*> > sqMatrix;

and I want to do this from the main.cpp :

QObject::connect(sqMatrix.at(0).at(0),SIGNAL(clicked())
                ,sqMatrix.at(5).at(5),SLOT(discoverThis()));

I have tried lots of things and done many researches but I cannot figure out how to do it properly.

Here I'm having the error :

QObject::connect: No such slot QPushButton::discoverThis()

Here are the corresponding .h and .cpp files :

square.h :

#ifndef SQUARE_H
#define SQUARE_H

#include <QPushButton>

class Square : public QPushButton
{
public:
    Square(const QString &text, QWidget *parent = 0);
    void mousePressEvent(QMouseEvent *e);
public slots:
    void discoverThis();
signals:
    void clicked();
};

#endif // SQUARE_H

square.cpp :

#include <QApplication>
#include <string>
#include "square.h"

#include <QMouseEvent>

Square::Square(const QString &text, QWidget *parent) : QPushButton(text,parent) {
    setFixedSize(16,16);
    setIcon(QIcon(":/images/images/square.png"));
}

void Square::mousePressEvent(QMouseEvent *e) {
    if(e->button() == Qt::LeftButton) {
        setIcon(QIcon(":/images/images/1.png"));
    }
    if(e->button() == Qt::RightButton) {
        setIcon(QIcon(":/images/images/flag.png"));
    }
}

void Square::discoverThis() {
    setIcon(QIcon(":/images/images/8.png"));
}

void Square::clicked() {
}

I'm a begginer so please be indulgent. I'm sure there are atrocious mistakes in my code.

Any help would be very appreciated.

Have a nice day.

Was it helpful?

Solution

The problem is you missed the Q_OBJECT macro in the class. See the "HERE" arrow.

#ifndef SQUARE_H
#define SQUARE_H

#include <QPushButton> 

class Square : public QPushButton
{
    Q_OBJECT     <---- HERE!

public:
    Square(const QString &text, QWidget *parent = 0);
    void mousePressEvent(QMouseEvent *e);

public slots:
    void discoverThis();

// +++ The signal "clicked()" is already declared in QPushButton +++
//signals:
//    void clicked();
};

#endif // SQUARE_H

Each subclass of a QObject needs the Q_OBJECT macro. This also triggers usually the moc (Meta Object Compiler) which automatically creates some additional method implementations (e.g. for signals and meta object handling.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top