我如何使用对话框上的确定和取消按钮

How do i use okay and cancel buttons on QDialogbox

我有一个名为“WinApp”的 QDialog 框,看起来像这样

,所以,当我单击确定时,必须将两个 lineedits 中输入的值分配给两个 QStrings,我该如何实现?因为截至目前,即使我单击“取消”,值仍被分配给 QStrings。

但如果我单击取消,则输入的值不应分配给 QString。

如果需要,我的 WinApp.h 的代码是

#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;
};

我的 WinApp.cpp 的代码是

#include "WinApp.h"

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

WinApp::~WinApp()
{
}

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

更新:

这是 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
    }
}

关闭对话框后,您可以获得其结果(即用户单击的按钮的值)。像这样:

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

来自 Qt 文档:https://doc.qt.io/qt-5/qdialog.html#result

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