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

I have inherited the QmainWindow class to use as the mainwindow for the application that I am building.
I have set the central widget as a pointer to another class, that I have created.
//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
When the user clicks on an action, this sets the central widget to another pointer to another widget class.
/*
*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 breaks when switching back and forth between views. And If I add a null point to the preceding view I lose the data when I go back to that view.
/*
*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);
How would I keep the state between the two views without creating a custom data structure or is this bad practice. I am most familiar with php and web dev so I am not sure if this is even the best way to go about this.
Thanks in advance

Not totally sure what your goal is. But if you are trying to permit someone the ability to go back to something they were working on, then perhaps you'd be better off using a tab widget instead of hiding the existence of that work?
QTabWidget documentation
Qt Tabbed Dialog example
So you'd make that your central widget, and plug the Post_Entry_Widget and Data_Entry_Widget instances under that. An advantage of that is that Qt manages the tab switching for you.
If you don't want tabs there is also a QStackedWidget, which just lets you programmatically switch between a set of widgets.

It is more complicated than it seems. The problem is, that when setCentralWidget() is called, current centralWidget() gets deleted. In order to preserve its contents, you need to remove it from the window by reparenting it to NULL or 0. Try to change your code to:
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);

Related

How to resize a QLabel displayed by a QWidgetAction after changing it's text

I use a QWidgetAction to add a header to a context menu (that will also show up on Windows, no matter what style is used, in contrast to addSection(), which does not always actually display the title).
The action's widget is a QLabel. It's text is changed by each invocation of the context menu. The menu is setup in the constructor of my class, and the QWidgetAction is added like so (all m_ variables are member variables declared in the header):
m_contextMenu = new QMenu(this);
m_menuTitle = new QLabel;
m_menuTitle->setAlignment(Qt::AlignCenter);
m_menuTitle->setMargin(4);
QWidgetAction *titleAction = new QWidgetAction(m_contextMenu);
titleAction->setDefaultWidget(m_menuTitle);
m_contextMenu->addAction(titleAction);
m_contextMenu->addSeparator();
When the menu is requested, the text of the label is changed and the menu is displayed like so:
m_menuTitle->setText(tr("%1 „%2“").arg(some_variable, some_other_variable));
...
m_contextMenu->exec(place_to_display);
When the label's text is set for the first time (with a short text the label's text is set to), everything is fine:
but when it's set to some longer text, the size remains the same and the text is cropped:
I tried to fix this, but the only working solution I found was to define the QActions displayed in the menu in the constructor, owned by this, setting the label's text, clearing the menu and adding the actions again, like so:
m_contextMenu->clear();
m_menuTitle->setText(tr("%1 „%2“").arg(some_variable, some_other_variable));
m_contextMenu->addAction(m_menuTitleAction);
m_contextMenu->addSeparator();
m_contextMenu->addAction(m_editAction);
m_contextMenu->addAction(m_deleteAction);
m_contextMenu->exec(place_to_display);
Is there a way to resize the title without rebuilding the menu each time?
The solution is to send a resize event instead:
m_menuTitle->setText(tr("%1 „%2“").arg(some_variable, some_other_variable));
...
QResizeEvent re(new_size, m_contextMenu->size());
qApp->sendEvent(m_contextMenu, &re);
This will set the QMenu's internal itemsDirty flag and will force geometry recalculation when the menu is shown. Note that the new size in the event does not matter, as the menu will aways resize based on its sizeHint()!
The QResizeEvent solution didn't really work for me (with a more complex widget), I found the generic solution by reading the QMenu and QAction source code.
m_widget->installEventFilter(this);
// and in my case m_widget->layout()->setSizeConstraint(QLayout::SetFixedSize);
bool SomeClass::eventFilter(QObject* watched, QEvent* event)
{
if (watched == m_widget && event->type() == QEvent::Resize) {
// Force QMenu to recalculate the geometry of this item
QActionEvent e(QEvent::ActionChanged, this);
qApp->sendEvent(m_contextMenu, &e);
}
...
}
QActionEvent triggers everything we need in QMenu: recalculating geometries, resizing the menu to its new size (if it's visible), etc.
This answer extends user362515's answer.
There is little more effort required if you change the size of a hidden widget action (e.g., because of its menu is currently collapsed).
Create a new class ActionWidget which derives publicly from QWidget.
Then override the showEvent method and implement it like this:
void ActionWidget::showEvent(QShowEvent* event)
{
QResizeEvent resize_event(QSize(), parentWidget()->size());
parentWidget()->adjustSize();
qApp->sendEvent(parentWidget(), &resize_event);
QWidget::showEvent(event);
}
Notice that adjustSize must be called on the parent widget of the action widget and the event must be sent to the parent widget.
Of course, you must also reimplement QWidgetAction::createWidget such that it returns an instance of the ActionWidget-class and make sure that ActionWidget reports a proper (updated) size hint.

How to retain set value on QSpinBox in QWidget when visiting this widget everytime?

I am having QSpinBox in QWidget where i set some value. Whenever i visit this widget next time, the spinbox takes initial value as zero instead of whatever value I set before.Is anyone having idea about it?
Thanks in advance.
Dialog:
Spin_Box::Spin_Box(QWidget parent)
: QDialog(parent),ui(new Ui::Spin_Box)
{
ui->setupUi(this);
/ Settings for title bar /
ui->headingTextEdit->setText("SPIN BOX");
/ Settings Range for Time spin boxes */
ui->fromHourSpinBoxShift1->setRange(0,23);
ui->fromMinSpinBoxShift1->setRange(0,59);
ui->fromSecSpinBoxShift1->setRange(0, 59);
}
Slot where dialog is opened:
MainWindow::on_actionSpin_Box_triggered()
{
Spin_Box Spin_BoxDialogue;
Spin_BoxDialogue.setModal(true);
Spin_BoxDialogue.exec();
}
As vahancho and Oleg Olivson stated in the comments, each time the function on_actionSpin_Box_triggerd() gets called a new instance of your Dialog is created. Therefore all values are those initialized.
If you want to keep previously inserted values you have to, either create the dialog only once (within your class where on_actionSpin_Box_triggered() is implemented) and reuse it by calling only exec() each time, or you store the values of the dialog in settings/... or whatever, to load them each time the dialog is opened.
Depending whether you would also need them after a program restarts, only the second approach would help.
Make Spin_BoxDialogue a pointer to Spin_Box a member of your MainWindow. So "MainWindow.h" should have this line inside class MainWindow's private section:
Spin_BoxDialogue* m_foo;
Initialize it and set it to Modal in MainWindow's constructor. Note that Spin_BoxDialogue should have a constructor that takes a pointer to its parent to take advantage of Qt's memory management.
MainWindow::MainWindow() : m_foo(new Spin_BoxDialogue){m_foo->setModal(true);}
Then change MainWindow::on_actionSpin_Box_triggered to this:
void MainWindow::on_actionSpin_Box_triggered(){m_foo->show();}

My widget doesn't show on the mainwindow. qt

in my program the senario is like this, user opens a xml file, the program reads it. Show the units and tests and when the user clicks on the desired test, the program needs to show its step. Since the number of steps always change i need to add the widget by code and delete them. But when i try to add a widget by code and set its position it doesn't show up on the main window. ( i am doing this with a seperate class just make things look neater)
Here is my sample code;
void CStepPanel::addstep()
{
QLabel *label1 = new QLabel("step1");
label1->move(450,50);
}
Do you know doesnt it work ? And how can i do that. Since i am new to qt and programming i am having a hard time about this.
Your widget should have a parent to be shown in an other widget or dialog. You should set a parent for the label. If you want it to be displayed on the main window then a pointer to your QMainWindow should be kept in the class CStepPanel (It could be assigned in the constructor of CStepPanel) :
QMainWindow * mainWindow;
And the addstep is like :
QLabel *label1 = new QLabel("step1");
label1->setParent(mainWindow);
label1->move(450,50);

How to properly clean-up a QWidget / manage a set of windows?

Let's say I have 2 windows in my application, and two classes responsible for them:
class MainWindow: public QMainWindow and class SomeDialog: public QWidget.
In my Main Window I have a button. When it is clicked, I need to display the second window. I do it this way:
SomeDialog * dlg = new SomeDialog();
dlg.show();
Now, the user does something in the window, and closes it. At this point I want to get some data from that window, and then, I suppose, I will have to delete dlg. But how do I catch the event of that window being closed?
Or is there another way not to have a memory leak? Maybe It would be better to create an instance of each window on startup, and then just Show()/Hide() them?
How do I manage such a case?
It is advised to use show() / exec() and hide() instead of dynamically creating the dialog every time you want to show it. Also use QDialog instead of QWidget.
In the constructor of your main window create it and hide it
MainWindow::MainWindow()
{
// myDialog is class member. No need to delete it in the destructor
// since Qt will handle its deletion when its parent (MainWindow)
// gets destroyed.
myDialog = new SomeDialog(this);
myDialog->hide();
// connect the accepted signal with a slot that will update values in main window
// when the user presses the Ok button of the dialog
connect (myDialog, SIGNAL(accepted()), this, SLOT(myDialogAccepted()));
// remaining constructor code
}
In the slot connected to the buttons's clicked() event simply show it, and if necessary pass some data to the dialog
void myClickedSlot()
{
myDialog->setData(data);
myDialog->show();
}
void myDialogAccepted()
{
// Get values from the dialog when it closes
}
Subclass from QWidget and reimplement
virtual void QWidget::closeEvent ( QCloseEvent * event )
http://doc.qt.io/qt-4.8/qwidget.html#closeEvent
Also it looks like the widget you want to show is a dialog. So consider using QDialog or it's subclasses. QDialog has useful signals you can connect to:
void accepted ()
void finished ( int result )
void rejected ()
I think you are looking for the Qt::WA_DeleteOnClose window flag: http://doc.qt.io/archives/qt-4.7/qt.html#WidgetAttribute-enum
QDialog *dialog = new QDialog(parent);
dialog->setAttribute(Qt::WA_DeleteOnClose)
// set content, do whatever...
dialog->open();
// safely forget about it, it will be destroyed either when parent is gone or when the user closes it.

How can I make a child widget standalone?

Suppose I have a main Widget, which is used to view some objects. The names of those objects are stored in a QListWidget. Now when a user selects one object (one item of the QListWidget), I want to open another widget in a separate window which takes the name of the object as an argument.
class MainWidget
{
Q_OBJECT
public slots:
void openSelection();
};
class ChildWidget
{
public:
ChildWidget(QString name, QWidget* parent = nullptr);
};
void MainWidget::openSelection()
{
QString selectedObjectName = ui->objectsNamesList->selectedItem()->text();
ChildWidget* detaildedWiew = new ChildWidget(selectedObjectName, this);
detaildedWiew->show();
}
When I do this, the child widget opens, but it has no space of its own. It is locked in the area of the parent. I need to set the children free, to run around the screen freely, independent of their parent. How can I do this? Is there some Qt way, or do I have to define some "pseudo child" relationship and develop a system to properly delete the pseudo children?
You can use QWidget::setWindowFlags(Qt::Window) to make your widget a separate window.
Also have a look at Qt::WindowFlags.
Not sure I got the question right...
The default constructor of QWidget may accept two arguments:
QWidget *parent = 0 is the parent of the new widget. If it is 0 (the default), the new widget will be a window. If not, it will be a child of parent, and be constrained by parent's geometry (unless you specify Qt::Window as window flag).
Qt::WindowFlags f = 0 (where available) sets the window flags; the default is suitable for almost all widgets, but to get, for example, a window without a window system frame, you must use special flags.
So, if you pass anything but NULL to parent, your wiget will not be a separate window, unless you set the second parameter as QT::Window. This is what's happening for you. So you'll need to either set the flag QT::Window, or make your own class, derive it from QWidget, and write a constructor that takes an additional argument which will be the pointer you need, while getting NULL as parent.