这个程序(Qt)的信号和槽的问题?

时间:2013-05-17 18:30:43

标签: c++ qt

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

welcome.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

welcome.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();
}

login.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

login.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);
}

2 个答案:

答案 0 :(得分:2)

w是范围本地变量,并在您connect之后立即删除。使它成为特定实例。

答案 1 :(得分:2)

connect期望指针(到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

welcome.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();
}