How to deal with "'MainWindow' does not refer to a value"?
-
Hello y'all,
I get it while trying to connect a signal from MainWindow class to the slot from the SecDialog class. Why I get an error?mainwindow.h:
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); signals: void bubaSignal(); private slots: void on_pushButton_clicked(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
mainwindow.cpp:
#include "mainwindow.h" #include "ui_mainwindow.h" #include "secdialog.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { SecDialog secDialog; secDialog.setModal(true); emit bubaSignal(); secDialog.exec(); }
secdialog.h:
#ifndef SECDIALOG_H #define SECDIALOG_H #include <QDialog> namespace Ui { class SecDialog; } class SecDialog : public QDialog { Q_OBJECT public: explicit SecDialog(QWidget *parent = nullptr); ~SecDialog(); public slots: void dubaSlot(); private: Ui::SecDialog *ui; }; #endif // SECDIALOG_H
secdialog.cpp
#include "secdialog.h" #include "ui_secdialog.h" #include "mainwindow.h" SecDialog::SecDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SecDialog) { ui->setupUi(this); connect(&MainWindow, SIGNAL(bubaSignal()), this, SLOT(dubaSlot())); <- error is here } SecDialog::~SecDialog() { delete ui; } void SecDialog::dubaSlot() { ui->label1->setText("duba slot works"); }
-
@ddryomyss
MainWindow
is a class/type, not an instance.connect()
only accepts instances, like thethis
you have for the slot.This is the wrong approach anyway. A dialog should never know about any main window. The
connect()
belongs in theMainWindow
class where you create the dialog instance, not in theSecDialog
class. -
@JonB said in How to deal with "'MainWindow' does not refer to a value"?:
This is the wrong approach anyway. A dialog should never know about any main window. The connect() belongs in the MainWindow class where you create the dialog instance, not in the SecDialog class.
K, I think I got it. Thanks!
-
@ddryomyss
Further.If you want to use a signal/slot approach here that is doable. However. If all you want to do is the
ui->label1->setText(...)
I think most people would rather expose a setter method in
SecDialog
which will set that text. (And potentially a getter method to similarly return it if it were, say, an editable widget.)SecDialog secDialog; secDialog.setLabel1Text("Some text"); secDialog.exec(); auto editableText = secDialog.editWidgetText();
Rather than a signal/slot approach for this. Depends what you're wanting to do.