基本上,有两种方法可以在不同类的实例之间传递信息(或动作):
您可以让两种形式中的一种意识到另一种形式,即给出
SecondForm这样的方法:
void setLabelTextAndShow(QString);
并从FirstForm 调用它。这意味着一些重要的事情:
FirstForm 必须知道 SecondForm 公共接口并且必须是
能够访问它(即必须至少有一个指向
SecondForm 实例)。
或者您使用 Qt 信号/槽内置机制使表单彼此不可知。
因此,在 SecondForm 中,您有一个 slot,而不是像上面那样的公共方法:
private slots:
void setLabelTextAndShow(QString);
在 FirstForm 中,您声明 signal:
signals:
void pushBttonClicked(QString lineEditText);
点击按钮时会“发射”:
void FirstForm::on_pushButton_clicked()
{
emit pushBttonClicked(ui->lineEdit->text());
this->close();
}
并被困在 SecondForm 插槽中:
void SecondForm::setLabelTextAndShow(QString text)
{
ui->label->setText(text);
this->show();
}
您必须在使用前连接信号和插槽。让它发生在 main 中:
#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();
}
使用第二种方法,您避免了在类之间创建依赖,这在可重用性方面非常好。