如何在 Qt 中将数据从一种形式传递到另一种形式?
我创建了一个 QWidgetProgect -> QtGuiApplication,我目前有两个表单。现在我想将数据从一种形式传递到另一种形式。
我怎样才能做到这一点?
谢谢。
textChanged
或textEdited
信号连接)假设您有两个窗口:FirstForm
和SecondForm
. 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();
}
您还可以使用指针从其他表单访问 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
}