0

我想链接两个页面,当程序运行时,点击“确定”后会显示欢迎页面。这是我的代码,但我不知道为什么它会出错!!!!有什么问题?

欢迎.h:

    #ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QLabel>
#include <QPushButton>

class welcome : public QWidget
{
    Q_OBJECT


public:
    welcome(QWidget *parent = 0);
    QLabel *wel;
    QPushButton *ok;

public slots:
    void open();
};



#endif // WIDGET_H

欢迎.cpp:

#include "welcome.h"
#include "login.h"

welcome::welcome(QWidget *parent)
    : QWidget(parent)
{
    this->setWindowTitle("Welcome");
    this->resize(250,120);
    wel = new QLabel("Welcome to your program",this);
    wel->setGeometry(65,30,150,20);
    ok = new QPushButton("Ok",this);
    ok->setGeometry(95,70,60,23);
    login w;
    connect(this->ok,SIGNAL(clicked()),w,SLOT(open()));
}
void welcome :: open()
{
    login w;
    w.show();
}

登录.h:

#ifndef LOGIN_H
#define LOGIN_H

#include <QWidget>
#include <QLabel>
#include <QLineEdit>
#include <QCheckBox>
#include <QPushButton>

class login : public QWidget
{
    Q_OBJECT

public:
    login(QWidget *parent = 0);
    QLabel *user,*pass;
    QLineEdit *inuser,*inpass;
    QCheckBox *showpass;
    QPushButton *ok,*reg;
};



#endif // LOGIN_H

登录.cpp:

#include "login.h"

login::login(QWidget *parent)
    : QWidget(parent)
{
    this->setWindowTitle("Login");
    this->resize(300,150);
    user = new QLabel("insert your username :",this);
    user->setGeometry(10,20,120,20);
    pass = new QLabel("insert your password :",this);
    pass->setGeometry(10,50,120,20);
    inuser = new QLineEdit(this);
    inuser->setGeometry(130,20,150,20);
    inpass = new QLineEdit(this);
    inpass->setGeometry(130,50,150,20);
    showpass = new QCheckBox("show password",this);
    showpass->setGeometry(130,80,100,15);
    ok = new QPushButton("login",this);
    ok->setGeometry(125,110,50,25);
    reg = new QPushButton("register",this);
    reg->setGeometry(180,110,50,25);
}
4

2 回答 2

2

w是作用域局部变量,并在您connect访问它之后立即被删除。使其成为特定于实例的。

于 2013-05-17T18:51:52.673 回答
2

connect期望指针(指向 a QObject)而不是对象,这就是您看到错误消息的原因。正如 Valeri Atamaniouk 所提到的,您提供w本地存储持续时间的事实也是致命的。您需要在堆上创建w一个成员welcome并声明它。还要注意析构函数的添加:

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QLabel>
#include <QPushButton>

#include "login.h"

class welcome : public QWidget
{
    Q_OBJECT


public:
    welcome(QWidget *parent = 0);
    ~welcome();
    QLabel *wel;
    QPushButton *ok;

public slots:
    void open();

private:
   login* w;
};

#endif //WIDGET_H

欢迎.cpp:

#include "welcome.h"

welcome::welcome(QWidget *parent)
    : QWidget(parent), w(new login)
{
    this->setWindowTitle("Welcome");
    this->resize(250,120);
    wel = new QLabel("Welcome to your program",this);
    wel->setGeometry(65,30,150,20);
    ok = new QPushButton("Ok",this);
    ok->setGeometry(95,70,60,23);
    connect(this->ok,SIGNAL(clicked()),w,SLOT(open()));
}
welcome::~welcome()
{
   delete w;
}
void welcome :: open()
{
    w->show();
}
于 2013-05-17T19:01:14.707 回答