简体   繁体   中英

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.

  1. 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;

  2. 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);}

  3. Then change MainWindow::on_actionSpin_Box_triggered to this:

    void MainWindow::on_actionSpin_Box_triggered(){m_foo->show();}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM