Как функцию заставить ждать, пока не выполнится работа в окне - Qt

190
24 марта 2018, 16:44

Имеется такой код:

bool Auth(int num)
{
Authentication AuthWindow;
AuthWindow.show();
if(AuthWindow.exec() == QDialog::Accepted)
{
    string login=AuthWindow.login,password=AuthWindow.password;
    if(!TryLogin(login,password))
        exit(EXIT_SUCCESS);
    AuthWindow.close();
    user(login, password);
    }else exit(EXIT_SUCCESS);
    return true;
}

Конечно же он не работает.
Как заставить функцию ждать, пока окно авторизации не завершит свою работу?

Answer 1

Необходимо чтоб authentication был наследником от QDialog, у которого нужно вызывать блокирующий метод QDialog::exec(). Совет на другую тему, в C++ обычно принято название классов писать с большой буквы, а название переменных с маленькой, я этого буду придерживаться в своем примере. Пример возможного класса Authentication:

authentication.h

#ifndef AUTHENTICATION_H
#define AUTHENTICATION_H
#include <QDialog>
namespace Ui {
class Authentication;
}
class Authentication : public QDialog
{
    Q_OBJECT
public:
    explicit Authentication(QWidget *parent = 0);
    ~Authentication();
    bool getAuthenticated() const;
private slots:
    void on_closeButton_clicked();
    void on_applyButton_clicked();
private:
    Ui::Authentication *ui;
};
#endif // AUTHENTICATION_H

authentication.cpp

#include "authentication.h"
#include "ui_authentication.h"
Authentication::Authentication(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Authentication)
{
    ui->setupUi(this);
}
Authentication::~Authentication()
{
    delete ui;
}
bool Authentication::getAuthenticated() const
{
    return ui->checkBox->isChecked();
}
void Authentication::on_closeButton_clicked()
{
    reject();
}
void Authentication::on_applyButton_clicked()
{
    accept();
}

На форме расположены checkbox (симулировать процесс аутентификации) и две кнопки "применить"(applyButton) и "закрыть"(closeButton).

Из основного окна вызывает вот так:

Authentication dialog(this);
if(dialog.exec() == QDialog::Accepted)
{
    //значит пользователь нажал кнопку "применить"
    bool authenticated  = dialog.getAuthenticated();
    qDebug() << "authenticated:" << authenticated;
} else
{
    //пользователь нажал "закрыть" или "крестик в углу"
}
READ ALSO
Передать анонимную функцию из Delphi в C++

Передать анонимную функцию из Delphi в C++

Здравствуйте, как можно передать анонимную функцию из Delphi в C++? Delphi:

183
QModbusDataUnit + float

QModbusDataUnit + float

Добрый день! Подскажие как получить float значения? Код для чтения регистров

205