How to pass signal and slot parameters to QObject::connect

88 Views Asked by At

I am receiving the errors:

Call to non-static member function without an object argument

and:

Cannot take the address of an rvalue of type 'void'

I have looked at the documentation here and many tutorials and forums, and I cannot find what is different about my code from theirs. The first error is regarding &BoardScreen::boardScreenClosed(), and the second is regarding &StartScreen::on_boardScreenClosed(), both in the connect() function parameters.

boardscreen.h:

#ifndef BOARDSCREEN_H
#define BOARDSCREEN_H

#include <QMainWindow>

namespace Ui {
class BoardScreen;
}

class BoardScreen : public QMainWindow
{
    Q_OBJECT

public:
    explicit BoardScreen(QWidget *parent = nullptr);
    ~BoardScreen();

signals:
    void boardScreenClosed();

private:
    Ui::BoardScreen *ui;
    QWidget *parentForm;;
};

#endif // BOARDSCREEN_H

startscreen.h:

#ifndef STARTSCREEN_H
#define STARTSCREEN_H

#include <QMainWindow>
#include <QLabel>
#include <QObject>
#include "boardscreen.h"
#include "playscreen.h"

namespace Ui {
class StartScreen;
}

class StartScreen : public QMainWindow
{
    Q_OBJECT

public:
    explicit StartScreen(QWidget *parent = nullptr);
    ~StartScreen();

private slots:
    void on_btn_play_clicked(); // Open the board screen
    void on_boardScreenClosed();

private:
    Ui::StartScreen *ui;
    PlayScreen *playScreen;
};

#endif // STARTSCREEN_H

startscreen.cpp:

#include "startscreen.h"
#include "ui_startscreen.h"
#include "boardscreen.h"

StartScreen::StartScreen(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::StartScreen)
{
    ui->setupUi(this);
    setWindowTitle("chesster");
    setGeometry(200, 85, 1500, 900);

     // Load logo
    QString path = R"(C:/user/path/to/logo.png)";
    QPixmap img(path);
    ui->lbl_logo->setPixmap(img);

    this->show();
}

StartScreen::~StartScreen()
{
    delete ui;
}

void StartScreen::on_btn_play_clicked()
{
    BoardScreen *boardScreen = new BoardScreen(this);
    boardScreen->show();

    connect(boardScreen, &BoardScreen::boardScreenClosed(), this, &StartScreen::on_boardScreenClosed());

    this->hide();
}


void StartScreen::on_boardScreenClosed()
{
    this->show();
}
2

There are 2 best solutions below

0
JarMan On BEST ANSWER

The problem is that you were using parentheses when passing the signal and slot to the connect function. That means you were actually calling those functions and passing the return value to connect() instead of passing the addresses of the functions themselves. The correct syntax should look like this:

connect(boardScreen, &BoardScreen::boardScreenClosed, this, &StartScreen::on_boardScreenClosed);
0
catfriendly On

As JarMan said, I needed to remove the parenthesis after the signal and slot names. The correct syntax for the connect() function is:

connect(boardScreen, &BoardScreen::boardScreenClosed, this, &StartScreen::on_boardScreenClosed);