7

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

我怎样才能做到这一点?

谢谢。

4

2 回答 2

16

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

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

信号和槽的示例:

假设您有两个窗口:FirstFormSecondForm. FirstForm在其 UI 上有一个QLineEdit,名为myTextEdit并且在其 UI 上SecondForm有一个QListWidget,名为myListWidget.

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

firstform.h:

class FistForm : public QMainWindow
{

...

private slots:
    void onTextBoxReturnPressed();

signals:
    void newTextEntered(const QString &text);

};

第一形式.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());
}

第二种形式.h

class SecondForm : public QMainWindow
{

...

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

第二种形式.cpp

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

主文件

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();
}
于 2011-06-01T11:49:11.303 回答
2

您还可以使用指针从其他表单访问 QTextEdit(假设这是您正在使用的)。

遵循 Venemo 的示例(其中 FirstForm 具有 QTextEdit 和 SecondForm 是您需要从中访问 QTextEdit 的那个):

firstform.h:

class FistForm : public QMainWindow
{

...

public:
    QTextEdit* textEdit();
};

firstform.cpp:

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

然后,您可以使用以下方式访问 SecondForm 中的 QTextEdit 文本(假设您的 FirstForm 实例称为 firstForm):

void SecondForm::processText()
{
    QString text = firstForm->textEdit()->toPlainText();
    // do something with the text
}
于 2011-06-01T16:18:05.770 回答