实现目标
有一MainWindow(主窗口)、有一Dialog(新建的窗口),之间互相传递一个QList对象。
实现方案
主窗口给新建的窗口传递参数
主窗口会持有一个新建窗口的指针,如下:
1
Waypoints_Dialog *waypoints_dlg = new Waypoints_Dialog;
因此新建窗口开一个小窗让主窗口设置即可(即使用一个public方法)
新建的窗口:
1 2 3 4 5 6
void Waypoints_Dialog::set_wayPointList (QList<wayPoint>& ls) { this ->wayPointList = ls; update_table (); update_waypoints_spin (); }
主窗口:
1 2 3 4 5 6 7 8 9
void MainWindow::on_menuWaypoints_triggered () { this ->waypoints_dlg->set_wayPointList (wayPointList); this ->waypoints_dlg->exec (); } void MainWindow::set_wayPointList (QList<wayPoint>& ls) { this ->wayPointList = ls; }
新建的窗口给主窗口传递参数
新建的窗口是没有主窗口的指针的,因此上面的方案不可行。
考虑使用信号与槽的方案实现(其实就是一个观察者模式,因为主窗口含有新建串口的指针,因此主窗口可以设置为观察者(槽),新建窗口为被观察者(信号)):
被观察者(新窗口):
信号声明(不需要实现,发送即可):
1 2
signals: void send_wayPointList (QList<wayPoint>& ls) ;
发送信号:
1 2 3 4
void Waypoints_Dialog::on_send_btn_clicked () { emit send_wayPointList (this ->wayPointList) ; QDialog::accept (); }
观察者(主窗口):
声明槽:
1 2
private slots: void set_wayPointList (QList<wayPoint>& ls) ;
定义之:
1 2 3
void MainWindow::set_wayPointList (QList<wayPoint>& ls) { this ->wayPointList = ls; }