QtT 如何在 QMainWindow 中更改中央小部件时保存数据/状态

QtT How To Save Data/State When Changing Central Widgets In QMainWindow

本文关键字:保存 数据 状态 小部 QMainWindow QtT      更新时间:2023-10-16

我继承了QmainWindow类,用作我正在构建的应用程序的主窗口。
我已将中央小部件设置为指向我创建的另一个类的指针。

//main window constructor
postEntryWidget = 0; // null pointer to another class that extends QWidget
dataEntryWidget = new Data_Entry_Widget; //extends QWidget
setCentralWidget(dataEntryWidget); //set the widget in the main window

当用户单击某个操作时,这会将中心小部件设置为指向另一个小部件类的另一个指针。

/*
 *this is the implementation of the slot that would be connected to the QAction
 *connected to the postEntryWidget slot
 */
if(!postEntryWidget)
    postEntryWidget = new Post_Entry_Widget;
setCentralWidget(postEntryWidget);
/*
 *this is the implementation of the slot that would be connected to the QAction
 *connected to the dataEntryWidget slot
 */
if(!dataEntryWidget)
    dataEntryWidget = new Post_Entry_Widget;
setCentralWidget(dataEntryWidget);

在视图之间来回切换时,这会中断。如果我向前面的视图添加一个空点,当我返回到该视图时,我会丢失数据。

 /*
 *this is the implementation of the slot that would be connected to the QAction
 *connected to the postEntryWidget slot
 */
dataEntryWidget = 0; //set the previous widget to a null pointer but loses data
if(!postEntryWidget)
    postEntryWidget = new Post_Entry_Widget;
setCentralWidget(postEntryWidget);

如何在不创建自定义数据结构的情况下保持两个视图之间的状态,或者这是不好的做法。 我最熟悉的是php和Web开发,所以我不确定这是否是最好的方法。

提前致谢

不完全确定你的目标是什么。 但是,如果您试图允许某人能够回到他们正在做的事情,那么也许您最好使用选项卡小部件而不是隐藏该工作的存在?

QTabWidget 文档

Qt 选项卡式对话框示例

因此,您可以将其作为您的中心小部件,并在其下插入Post_Entry_WidgetData_Entry_Widget实例。 这样做的一个优点是Qt为您管理标签切换。

如果你不想要标签,还有一个QStackedWidget,它只是让你以编程方式在一组小部件之间切换。

它比看起来更复杂。问题是,当调用setCentralWidget()时,当前centralWidget()被删除。为了保留其内容,您需要通过将其重新设置为父级来将其从窗口中删除 NULL0 .尝试将代码更改为:

if(!postEntryWidget)
    postEntryWidget = new Post_Entry_Widget;
if (centralWidget()) centralWidget()->setParent(0); //reparent if exists
setCentralWidget(postEntryWidget);
/*
...
*/
if(!dataEntryWidget)
    dataEntryWidget = new Post_Entry_Widget;
if (centralWidget()) centralWidget()->setParent(0); //reparent if exists
setCentralWidget(dataEntryWidget);