C++ QtT在QMainWindow中更改中心窗口小部件时如何保存数据/状态
我继承了QmainWindow类,用作我正在构建的应用程序的主窗口。C++ QtT在QMainWindow中更改中心窗口小部件时如何保存数据/状态,c++,qt,user-interface,C++,Qt,User Interface,我继承了QmainWindow类,用作我正在构建的应用程序的主窗口。 我已经将中心小部件设置为指向我创建的另一个类的指针 //main window constructor postEntryWidget = 0; // null pointer to another class that extends QWidget dataEntryWidget = new Data_Entry_Widget; //extends QWidget setCentralWidget(dataEntryWid
我已经将中心小部件设置为指向我创建的另一个类的指针
//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开发,所以我不确定这是否是最好的方法
提前感谢我不完全确定你的目标是什么。但是如果你想让某人能够回到他们正在做的事情上,那么也许你最好使用一个标签小部件,而不是隐藏工作的存在 因此,您可以将其作为您的中心小部件,并将
Post\u Entry\u小部件
和Data\u Entry\u小部件
实例插入其中。这样做的一个优点是,Qt为您管理选项卡切换
如果您不需要选项卡,还有一个,它只允许您通过编程在一组小部件之间切换。它比看起来更复杂。问题是,当调用
setCentralWidget()
时,当前的centralWidget()
会被删除。为了保留其内容,您需要将其从窗口中删除,方法是将其重新出租为NULL
或0
。尝试将代码更改为:
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);
取自Qt文档:
void QMainWindow::setCentralWidget(QWidget*widget)
将给定的小部件设置为主窗口的中心小部件。注意:QMainWindow拥有小部件指针的所有权,并在适当的时候将其删除。