如何在Qt中从一个表单传递数据到另一个表单?

7

如何在Qt中从一个表单传递数据到另一个表单?

我已经创建了一个QWidgetProgect -> QtGuiApplication,现在有两个表单。现在我想从一个表单传递数据到另一个表单。

我该如何实现这个功能?

谢谢。


我可以帮助你,但你需要告诉我想要在它们之间传递什么类型的数据。 - Venemo
@Venemo:我在表单1中输入的数据,应该能够在表单2中获取。 - Bokambo
2个回答

16

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

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

使用信号和槽的示例:

假设您有两个窗口:FirstFormSecondFormFirstForm 在其用户界面上有一个名为 myTextEditQLineEdit,而 SecondForm 在其用户界面上有一个名为 myListWidgetQListWidget

我还假设您在应用程序的 main() 函数中创建了这两个窗口。

firstform.h:

class FistForm : public QMainWindow
{

...

private slots:
    void onTextBoxReturnPressed();

signals:
    void newTextEntered(const QString &text);

};

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());
}

secondform.h

class SecondForm : public QMainWindow
{

...

public slots:
    void onNewTextEntered(const QString &text);
};

secondform.cpp

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

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();
}

@user662285 - 添加了一个示例 - Venemo
@Venemo:抱歉,我没听懂你的意思,请问你能否对上面的例子进行修改?谢谢。 - Bokambo
哇..太感谢了..一直在寻找类似的东西..谢谢StackOverflow.. - RicoRicochet
嗨@Venemo:我在你的代码中遇到了一个问题。我也想从first.cpp发出信号,以便在second.cpp中更改某些内容。但是我完全按照你的示例操作(除了second.show();因为我不想一开始就显示第二个表单)。有人能帮帮我吗? - H.Ghassami
@H.Ghassami 是的。在这里提问:http://stackoverflow.com/questions/ask :) - Venemo
显示剩余5条评论

2

你也可以使用指针从另一个窗体访问QTextEdit(假设您正在使用它)。

跟随Venemo的示例(其中FirstForm拥有QTextEdit,而SecondForm是您需要从QTextEdit访问的窗体):

firstform.h:

class FistForm : public QMainWindow
{

...

public:
    QTextEdit* textEdit();
};

firstform.cpp:

QTextEdit* FirstForm::textEdit()
{
    return ui->myTextEdit;
}

您可以通过以下方式访问QTextEdit在SecondForm中的文本(假设您的FirstForm实例名为firstForm):
void SecondForm::processText()
{
    QString text = firstForm->textEdit()->toPlainText();
    // do something with the text
}

我们能否将QLineEdit中的数据传递到QListWidget中?如何实现?我的需求是,当我在文本框中输入内容并在下一个表单中点击“确定”时,它应该被添加到列表小部件中。 - Bokambo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接