将值从第一个窗口传递到第二个窗口按下按钮,按下按钮后应隐藏第一个窗口

时间:2017-12-16 12:47:23

标签: c++ qt

此项目中有两个Windows。第一个是命名为firstform而另一个命名为seconform。

在第一个表单中,用户可以在QlineEdit上键入,然后单击按钮。 firstform close和secondform将打开,在标签的第二个窗口中,应显示键入的那个。

这意味着第一个窗口中lineEdit中的数据应传递给第二个窗口的标签

1 个答案:

答案 0 :(得分:0)

基本上,有两种方法可以在不同类的实例之间传递信息(或操作):

你可以让两种形式中的一种知道另一种形式,即给予 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();
}

使用第二种方法,您避免在类之间创建依赖,这在可重用性方面非常好。

相关问题