以下是您可能想尝试的一些选项:
- 如果一个表单拥有另一个表单,您可以在另一个表单中创建一个方法并调用它
- 你可以使用Qt的Signals and slots机制,用文本框在表单中生成一个信号,并将它连接到你在其他表单中创建的插槽(你也可以将它与文本框的
textChanged或textEdited连接起来信号)
信号和槽示例:
假设您有两个窗口:FirstForm 和 SecondForm。 FirstForm 在其 UI 上有一个 QLineEdit,名为 myTextEdit,SecondForm 在其 UI 上有一个 QListWidget,名为 myListWidget。
我还假设您在应用程序的 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();
}