Displaying and retrieving a QMessageBox result from outside a QObject

I am trying to display and get a message box outside of the QObject class. It seems I can generate a dialog like this:

#include <iostream>

#include <QApplication>
#include <QtConcurrentRun>
#include <QMessageBox>

class DialogHandler : public QObject
{
Q_OBJECT

signals:
  void MySignal();

public:
  DialogHandler()
  {
    connect( this, SIGNAL( MySignal() ), this, SLOT(MySlot()) );
  }

  void EmitSignal()
  {
    emit MySignal();
  }

public slots:
  void MySlot()
  {
    QMessageBox* dialog = new QMessageBox;
    dialog->setText("Test Text");
    dialog->exec();
    int result = dialog->result();
    if(result)
    {
      std::cout << "ok" << std::endl;
    }
    else
    {
      std::cout << "invalid" << std::endl;
    }
  }
};

#include "main.moc" // For CMake automoc

void MyFunction(DialogHandler* dialogHandler)
{
  dialogHandler->EmitSignal();
}

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);

  DialogHandler* dialogHandler = new DialogHandler;

  MyFunction(dialogHandler);

  return app.exec();
}

To return the result to MyFunction, it seems that you just need to pass the object to fill the result as follows:

#include <iostream>

#include <QApplication>
#include <QtConcurrentRun>
#include <QMessageBox>

class DialogHandler : public QObject
{
Q_OBJECT

signals:
  void MySignal(int* returnValue);

public:
  DialogHandler()
  {
    connect( this, SIGNAL( MySignal(int*) ), this, SLOT(MySlot(int*)), Qt::BlockingQueuedConnection );
  }

  void EmitSignal(int* returnValue)
  {
    emit MySignal(returnValue);
  }

public slots:
  void MySlot(int* returnValue)
  {
    std::cout << "input: " << *returnValue << std::endl;
    QMessageBox* dialog = new QMessageBox;
    dialog->addButton(QMessageBox::Yes);
    dialog->addButton(QMessageBox::No);
    dialog->setText("Test Text");
    dialog->exec();
    int result = dialog->result();
    if(result == QMessageBox::Yes)
    {
      *returnValue = 1;
    }
    else
    {
      *returnValue = 0;
    }
  }
};

#include "main.moc" // For CMake automoc

void MyFunction(DialogHandler* dialogHandler)
{
  int returnValue = -1;
  dialogHandler->EmitSignal(&returnValue);

  std::cout << "returnValue: " << returnValue << std::endl;
}

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);

  DialogHandler* dialogHandler = new DialogHandler;

  QtConcurrent::run(MyFunction, dialogHandler);

  std::cout << "End" << std::endl;
  return app.exec();
}

Does that seem reasonable? Is there a better way to do this?

+3
source share
1 answer

, , . , , QObject, . exec. , , , . , , , , . , customEvent ( ), , .

, , . , , .

+1

Source: https://habr.com/ru/post/1776748/


All Articles