开发者

About signals and slots in qt

开发者 https://www.devze.com 2023-01-08 02:36 出处:网络
I don\'t know how to connect two forms, I am able to open second form but cannot access the first form.

I don't know how to connect two forms, I am able to open second form but cannot access the first form.

My program:

#include<QApplication>
#include<QLabel>
#include<QPushButton>
#include<QGridLayout>

class form1
{
    public:
        QWidget *window1;
        QLabel *l1;
        QPushButton *b1;
        QGridLayout *gl;
        form1(){}
        void setup1();
        void show1();


};

void form1::setup1()
{
    window1=new QWidget();
    gl=new QGridLayout(window1);
    l1=new QLabel("I AM IN FORM1",window1);
    b1=new QPushButton("NEXT",window1);
    gl->addWidget(l1,0,0);
    gl->addWidget(b1,1,0);
}
void form1::show1()
{
    window1->show();
}

class form2
{
    public:
        QWidget *window2;
        QPushButton *b2;
        form2(){}
        void setup2();
        void show2();

};

void form2::setup2()
{
    window2=new QWidget();
    b2=new QPushButton("NEXT",window2);
}
void form2::show2()
{
    window2->show();
}


class Myclass:public QObject,public form1,public form2
{


    public slots:
        void open();
        void back();
    public:
        Myclass()
        { 
            setup1();
            setup2();
       开发者_运维百科     QObject::connect(b1,SIGNAL(clicked()),window1,SLOT(open()));
            QObject::connect(b2,SIGNAL(clicked()),window2,SLOT(back()));
        }


};

void Myclass::open()
{
    //window1->hide();
    //window2->show();
    show2();
}

void Myclass::back()
{
    window2->hide();
    l1->setText("BACK FROM FORM2");
    window1->show();
}

int main(int argc,char *argv[])
{
    QApplication app(argc,argv);
    Myclass *m=new Myclass();
    m->show1();
    return app.exec();
}


Mhm how does the first one work? Both methods open() and back() belong to MyClass. But your connects go to window1 and window2. Try if it works for "this" instead of window1/2.


When i start your program. I get this runtime qt warnigs:

Object::connect: No such slot QWidget::open() in question.h:44
Object::connect: No such slot QWidget::back() in question.h:45

So your connects are invalid. The slots are defined in Myclass not in window1 and window2. Replace with

QObject::connect(b1,SIGNAL(clicked()),this,SLOT(open()));
QObject::connect(b2,SIGNAL(clicked()),this,SLOT(back()));

or shorter:

connect(b1,SIGNAL(clicked()),this,SLOT(open()));
connect(b2,SIGNAL(clicked()),this,SLOT(back()));

and you get the expected behavior.

0

精彩评论

暂无评论...
验证码 换一张
取 消