I
I
Igor Mitrakov2019-05-18 12:16:29
Qt
Igor Mitrakov, 2019-05-18 12:16:29

How to pass parameter to parent class function in Qt C++?

Hello. There was a problem when passing a parameter to a parent class function using slot signals.
Used lambda function. Everything inside the class is great.
parent.h

class Rashod : public QWidget
{
  Q_OBJECT
public:
  explicit Rashod(QWidget *parent = nullptr);
private:
  QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
  QVBoxLayout *vblay = new QVBoxLayout();
  QPushButton *add_btn = new QPushButton("Добавить");

public slots:
  void show_add_btn(QString s);
};

parent.cpp
void Rashod::show_add_btn(QString s)
{
  add_btn->show();
  QLabel *knt = new QLabel(s);
  vblay->addWidget(knt, 0);
  child *chuld = new chuld(this);
}

child.h
class add_widget : public QWidget
{
  Q_OBJECT
public:
  explicit add_widget(QWidget *parent);
private:
  QPushButton *add = new QPushButton("Добавить");
  QString FIO;
};

child.cpp
add_widget::add_widget(QWidget *parent) : QWidget(parent)
{
  connect(this->add, &QPushButton::clicked, [=](){parent->show_add_btn(FIO);});
}

child.cpp:31: error: 'class QWidget' has no member named 'show_add_btn'
connect(this->add, &QPushButton::clicked, [=](){parent->show_add_btn(FIO);});
^~~~~~~~~~~~

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly, 2019-05-18
@vt4a2h

You have a few options:
1) Use the old join syntax and make show_add_btn a slot
2) Use qobject_cast in the lambda to cast the object to the right type
3) Use static_cast to cast in the lambda if you're sure it's the right object
4) Redesign the architecture so that castes are not needed at all. For example, so that the slot is connected to the signal by some factory or its analogue. I vote for this option.

V
vanyamba-electronics, 2019-05-18
@vanyamba-electronics

QObject::connect(this->add, &QPushButton::clicked, parent, &Rashod::show_add_btn);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question