0

I am trying to connect signals send by buttons in one class with slots of both child and parent classes. Here is an example that reproduces the problem:

ErrorClass.cpp

#include "errorclass.h"

ErrorClass::ErrorClass(QPushButton *button) : QObject()
{
    this->button = button;
}
void ErrorClass::makeConnectHappen()
{
    connect(button, SIGNAL(pressed()), this, SLOT(exampleSlot()));
}
//SLOT
void ErrorClass::exampleSlot()
{
    qDebug() << "ExampleSlot was here";
}

ErrorClassChild.cpp

#include "errorclasschild.h"

ErrorClassChild::ErrorClassChild(QPushButton *button) : ErrorClass(button)
{
    makeConnectHappen();
}
void ErrorClassChild::makeConnectHappen()
{
    ErrorClass::makeConnectHappen();
    connect(button, SIGNAL(released()), this, SLOT(exampleChildSlot()));
}
//SLOT
void ErrorClassChild::exampleChildSlot()
{
    qDebug() << "exampleChildSlot was here";
}

and finally standard MainWindow.cpp with a QPushButton

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "errorclasschild.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ErrorClassChild ecc(ui->pushButton);
}
MainWindow::~MainWindow()
{
    delete ui;
}

Where makeConnectHappen() is a virtual function in ErrorClass.h which is inherited and expanded by ErrorClassChild. I hope this will be clear.

When I compile and run the program there is Apllication Message

QObject::connect: No such slot ErrorClass::exampleChildSlot() in ../QListWidgetProblem/errorclasschild.cpp:11
QObject::connect:  (sender name:   'pushButton')

Now, when I put exampleChildSlot() in the parent as a pure virtual slot the error disappears but no qDebug() message is shown.

How make the connect with parents and children slots at the same time? Or is my idea completaly wrong?

Mat
  • 202,337
  • 40
  • 393
  • 406

2 Answers2

2

Q_OBJECT is not a property, it is a macro, so it is cannot be inherited. So if you would like to use signals-slots in your class (even if it is derived from class, where Q_OBJECT already is), you should add it to your class. There already was discussion on this topic here , so it could help you.

Community
  • 1
  • 1
Shf
  • 3,463
  • 2
  • 26
  • 42
1

You should rather use a virtual slot (the Qt doc explicitely say they can be virtual) :

Put these declarations in your base class

class ErrorClass : public QObject{

    Q_OBJECT
//...   
    void makeConnectHappen();    

public slots:
    virtual void exampleSlot();

}

Then, implement makeConnectHappen() for the base class exactly the way you did, and you'll only have to reimplement the slot in the derived class. Then, when the button will emit the pressed() signal, it will trigger the correct slots depending on the class of the objects you instantiated with this button.

JBL
  • 12,588
  • 4
  • 53
  • 84