简体   繁体   中英

C++ “was not declared in this scope” compile error

I'm new to C++ and QT, I'm using QT Creator, I created a QT Widget project named nGui, added a QT-QT Designer Form Class named mydlg, I've been trying to create a button in a window, when you click it opens another window while the original windows keeps showing. And here's my codes, but it always show the error: 'my2'was not declared in this scope. I have declared 'my2' in widget.h, and I included the widget.h file in mydlg.cpp, I don't know where is wrong, can someone help me out? Thank you so much!

mydlg.cpp

#include "mydlg.h"
#include "ui_mydlg.h"
myDlg::myDlg(QWidget *parent) :
QDialog(parent),
ui(new Ui::myDlg)

{
     ui->setupUi(this);
}

myDlg::~myDlg()

{

    delete ui;

}


void myDlg::on_pushButton_clicked()

{

     my2.show();

}

widget.h

#ifndef WIDGET_H

#define WIDGET_H

#include <QWidget>

#include"mydlg.h"

namespace Ui 
{
    class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

    public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

    private:
    Ui::Widget *ui;
    myDlg my2;
    private slots:
    void on_pushButton_clicked();
};

 #endif // WIDGET_H

main.cpp

#include <QtGui/QApplication>

#include "widget.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

my2Widget类中声明,但是您试图在myDlg类的成员函数中访问它。

Try replacing my2.show() with show() When you are writing in the myDlg class you are writing the behaviour of every object that can be instantiated from that class (including my2 ).

It does not make sense to refer to my2 within the MyDlg class then, since someone else using your class could instead instantiate another object called (for example) my3 with it instead. What you want to do is tell the compiler when on _pushButton_clicked() is called on an object of class MyDlg go ahead and call the show() function on the same object. You can do this by writing this->show() or simply show() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM