How to transfer data between two QT windows?
In Qt, there are several ways to transfer data between two windows.
- Passing data through constructors: When creating the second window, pass the necessary data as a parameter to the constructor of the second window. The second window can receive and store the passed data in its constructor.
// 第一个窗口
SecondWindow secondWindow(data);
secondWindow.show();
// 第二个窗口的构造函数
SecondWindow::SecondWindow(DataType data, QWidget *parent)
: QWidget(parent), m_data(data)
{
// 使用传递的数据
// ...
}
- Passing data through member functions: You can define a public member function in the second window and pass data by calling this function.
// 第一个窗口
SecondWindow secondWindow;
secondWindow.setData(data);
secondWindow.show();
// 第二个窗口的成员函数
void SecondWindow::setData(DataType data)
{
m_data = data;
// 使用传递的数据
// ...
}
- By using signals and slots to pass data: you can define a signal and a slot function, emit the signal and pass the data in the first window, and connect the signal to the slot function in the second window to receive the data.
// 第一个窗口
emit dataPassed(data);
// 第二个窗口的槽函数
void SecondWindow::onDataPassed(DataType data)
{
// 使用传递的数据
// ...
}
// 连接信号与槽
connect(firstWindow, &FirstWindow::dataPassed, secondWindow, &SecondWindow::onDataPassed);
The three common methods mentioned above can be chosen based on specific needs and circumstances.