如何在Qt中将数据从一种形式传递到另一种形式?

use*_*285 7 qt qt4 qwidget

如何在Qt中将数据从一个表单传递到另一个表单?
我创建了一个QWidgetProgect - > QtGuiApplication,我目前有两种形式.现在我想将数据从一个表单传递到另一个表单.

我怎样才能做到这一点?

谢谢.

Ven*_*emo 16

以下是您可能想要尝试的一些选项:

  • 如果一个表单拥有另一个表单,则可以在另一个表单中创建一个方法并调用它
  • 您可以使用Qt的信号和插槽机制,使用文本框在表单中发出信号,并将其连接到您在其他表单中创建的插槽(您也可以将其与文本框textChangedtextEdited信号连接)

信号和插槽示例:

我们假设您有两个窗口:FirstFormSecondForm.在其用户界面上FirstForm有一个QLineEdit名字myTextEdit,SecondFormQListWidget在其用户界面上有一个名为myListWidget.

我还假设您在main()应用程序的功能中创建了两个窗口.

firstform.h:

class FistForm : public QMainWindow
{

...

private slots:
    void onTextBoxReturnPressed();

signals:
    void newTextEntered(const QString &text);

};
Run Code Online (Sandbox Code Playgroud)

firstform.cpp

// Constructor:
FistForm::FirstForm()
{
    // Connecting the textbox's returnPressed() signal so that
    // we can react to it

    connect(ui->myTextEdit, SIGNAL(returnPressed),
            this, SIGNAL(onTextBoxReturnPressed()));
}

void FirstForm::onTextBoxReturnPressed()
{
    // Emitting a signal with the new text
    emit this->newTextEntered(ui->myTextEdit->text());
}
Run Code Online (Sandbox Code Playgroud)

secondform.h

class SecondForm : public QMainWindow
{

...

public slots:
    void onNewTextEntered(const QString &text);
};
Run Code Online (Sandbox Code Playgroud)

secondform.cpp

void SecondForm::onNewTextEntered(const QString &text)
{
    // Adding a new item to the list widget
    ui->myListWidget->addItem(text);
}
Run Code Online (Sandbox Code Playgroud)

main.cpp中

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    // Instantiating the forms
    FirstForm first;
    SecondForm second;

    // Connecting the signal we created in the first form
    // with the slot created in the second form
    QObject::connect(&first, SIGNAL(newTextEntered(const QString&)),
                     &second, SLOT(onNewTextEntered(const QString&)));

    // Showing them
    first.show();
    second.show();

    return app.exec();
}
Run Code Online (Sandbox Code Playgroud)