htmlamateur htmlamateur - 3 months ago 10
C++ Question

How to transfer parameter from constructor into slot?

I am doing a small exercise with Qt. As I know, slot

save_clicked
brings only type of parameter. So how can I transfer
userid
into slot
save_clicked
in file
MyClass.cpp
for processing below ?

MyClass.h

class MyClass : public QWidget
{
Q_OBJECT

public:
MyClass(QString userid, QString lastname, QString firstname, QWidget *parent = 0);
~MyClass();

public slots:
void save_clicked(QString userid);

private:
Ui::MyClass ui;
};

#endif // MYCLASS_H


MyClass.cpp

MyClass::MyClass(QString userid, QString lastname, QString firstname, QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
...........
...........
connect(ui.save, SIGNAL(clicked()), this, SLOT(save_clicked(QString)));
}

void MyClass::save_clicked(QString userid)
{
// process userid here
}

Answer

Better than use signals/slots just use a variable. It's the goal of a class. Add something like :

private:

QString userId;

And in your constructor add :

MyClass::MyClass(QString userid, QString lastname, QString firstname, QWidget *parent)
: QWidget(parent)
{
    ui.setupUi(this);
    this.userId=userid;

}

Like this you can use userId like you want and where you want into your class.

EDIT :

add in your .h

private slots:
    void on_saveButton_clicked();

and in your .cpp

void MyClass::on_saveButton_clicked()
{
    // you can use userId here
}

If you use Qt Creator those functions can add automatically in the UI design interface

Comments