mlbk86
mlbk86

Reputation: 33

Call class function by signal&slot system

I'm new to Qt so my question may be trivial. But I couldn't find proper answer or maybe I didn't really get the idea of signals & slots.

I have a MainWindow with four radio buttons and a class "Data" with no GUI representation. What I'm trying achieve is to set some property in class when radio button is checked.

Here is my header for class:

#include <QObject>

class Data : public QObject
{
    Q_OBJECT
public:
    explicit Data(QObject *parent = 0);
    ~Data();

signals:

public slots:
    void setTextOrientation(int data);

private:
    int textOrientation;
};

Here is the constructor for MainWindow:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    data = new Data();
    ui->setupUi(this);
    connect(ui->textOrientRB0, SIGNAL(toggled(true)), &data, SLOT(setTextOrientation(int)));
}

and the error:

mainwindow.cpp:10: error: C2664: 'QMetaObject::Connection QObject::connect(const QObject *,const char *,const char *,Qt::ConnectionType) const' : cannot convert argument 3 from 'Data **' to 'const QObject *'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

Upvotes: 2

Views: 151

Answers (3)

Johnny Thunderman
Johnny Thunderman

Reputation: 976

QObject::connect expects that the third argument is pointer to QObject. In your example you pass &data as third argument. &data is not pointer to QObject. It is pointer to pointer. Pass just data instead. This should solve compile error.

May be there will be another run-time error, since toggled has one argument of type bool and setTextOrientation has one argument of type int.

For compiler time checking of signal/slot compatibility (compatibility of the 2nd and 4th parameter of connect) you can use following syntax:

QObject::connect(ui->textOrientRB0, &QAbstractButton::toggled, data, &Data::setTextOrientation);

Upvotes: 0

kiss-o-matic
kiss-o-matic

Reputation: 1181

What does Data look like in the header file? It looks like you're passing a pointer to a pointer to Data, when you need to pass it pointer to Data.

If data is indeed type Data*, then the call should be

connect(ui->textOrientRB0, SIGNAL(toggled(true)), data, SLOT(setTextOrientation(int)));

Would need to see the header file to be sure, but I assume it is based on it's initialization.

Upvotes: 1

BЈовић
BЈовић

Reputation: 64223

You passed pointer to pointer, instead of pointer, here :

connect(ui->textOrientRB0, SIGNAL(toggled(true)), &data, SLOT(setTextOrientation(int)));

it should have been :

connect(ui->textOrientRB0, SIGNAL(toggled(true)), data, SLOT(setTextOrientation(int)));

At least, this is what the compiler is telling you.

Upvotes: 2

Related Questions