the_learnist
the_learnist

Reputation: 69

How do i use okay and cancel buttons on QDialogbox

i have a QDialog box named "WinApp" , it looks like this enter image description here

, so , when i click ok , the values entered inside two lineedits must be assigned to two QStrings, How can i achieve this ? Because as of now , even if i click "cancel" the values are still being assigned to QStrings.

but if i click cancel the values entered should not be assigned to QStrings.

if needed the code for my WinApp.h is

#include <QtWidgets/qdialog.h>
#include "ui_WinApp.h"

class WinApp : public QDialog, public Ui::WinApp
{
    Q_OBJECT

public:
    WinApp(QWidget *parent = Q_NULLPTR);
    ~WinApp();
    
    QString getDialogueValue();

private slots:

private:
    Ui::WinApp ui;
};

the code for my WinApp.cpp is

#include "WinApp.h"

WinApp::WinApp(QWidget *parent)
    : QDialog(parent)
{
    ui.setupUi(this);
}

WinApp::~WinApp()
{
}

QString WinApp::getDialogueValue()
{
    return ui.lineEdit->text();
}

UPDATE:

This is the code for Mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtCore>
#include <QtGui>
#include <sstream>
#include <QtWidgets/qmessagebox.h>
#include <QtWidgets/qlistwidget.h>

using namespace std;

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->My_listwidget->addItem("New York");
    ui->My_listwidget->addItem("Glasgow");
    ui->My_listwidget->addItem("Mumbai");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_My_listwidget_itemDoubleClicked(QListWidgetItem* item)
{
    QString test = item->text();
    std::string test_s = test.toStdString();

    if (test_s.find("New York") != std::string::npos) // check if item contains text "New York"
    {
        WinApp winApp;
        winApp.setModal(true);   //Displaying the window here
        winApp.exec();
        
        QString testo =winApp.getDialogueValue(); // Getting the value from 1st line edit here from getter function and assignment is happening here. 

         item->setText(testo);    
         item->setData(CapitalRole, testo);
    }
    
    if (test_s.find("Glasgow") != std::string::npos) 
    {
    // show another dialog box asking some questions
    }
    if (test_s.find("Mumbai") != std::string::npos) 
    {
    // show another dialog box asking some questions
    }
}

Upvotes: 0

Views: 644

Answers (1)

Gregor Budweiser
Gregor Budweiser

Reputation: 238

Once your dialog is closed you can get its result (i.e. the value of the button that the user clicked). Something like this:

WinApp dialog;
dialog.exec();
if (dialog.result() == QDialog::Accepted) {
    yourString = dialog.getDialogueValue();
}

From the Qt docs: https://doc.qt.io/qt-5/qdialog.html#result

In general returns the modal dialog's result code, Accepted or Rejected.

Upvotes: 4

Related Questions