这个项目中有两个Windows。第一个是命名为firstform而另一个命名为seconform。
在firstform中,用户可以在QlineEdit上键入,然后单击按钮。 firstform close和secondform将打开,在标签的第二个窗口中,应显示键入的那个。
这意味着第一个窗口中qlineEdit中的数据应传递给第二个Windows标签
基本上,有两种方法可以在不同类的实例之间传递信息(或操作):
您可以让两种形式中的一种知道另一种形式,即给SecondForm
这样的方法:
void setLabelTextAndShow(QString);
并从FirstForm
调用它。这意味着一些重要的事情:FirstForm
必须知道SecondForm
公共接口,并且必须能够访问它(即必须至少有一个指针到SecondForm
实例)。
或者您使用Qt信号/插槽内置机制保持表单彼此不可知。
所以,在SecondForm,而不是像上面的公共方法,你有一个slot
:
private slots:
void setLabelTextAndShow(QString);
而在FirstForm中你宣布一个signal
:
signals:
void pushBttonClicked(QString lineEditText);
单击pushButton时将“发出”:
void FirstForm::on_pushButton_clicked()
{
emit pushBttonClicked(ui->lineEdit->text());
this->close();
}
并陷入SecondForm插槽:
void SecondForm::setLabelTextAndShow(QString text)
{
ui->label->setText(text);
this->show();
}
在使用之前必须连接信号和插槽。让它发生在主要:
#include "firstform.h"
#include "secondform.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
FirstForm f1;
SecondForm f2;
QObject::connect(&f1, SIGNAL(pushBttonClicked(QString)), &f2, SLOT(setLabelTextAndShow(QString)));
f1.show();
return app.exec();
}
使用第二种方法,您可以避免在类之间创建依赖关系,这在可重用性方面非常好。