suma
suma

Reputation: 728

calling quit() method of QApplication

if i try to use quit() method directly, it is compiling perfectly, however during runtime there comes an error saying "Object::connect: No such slot myClass::quit()." so to avoid this, is there any way? by using a method quitPicture()(defined as slot) the application is working fine. is this the only solution?

myClass::myClass(QWidget *parent)
    : QWidget(parent)
{
    QWidget *window = new QWidget;
    window->setWindowTitle(QObject::tr("Class"));

    QPushButton *quitButton = new QPushButton("&Quit");
//    QObject::connect(quitButton, SIGNAL(clicked()), this, SLOT(quit()));      //showing run time error
    QObject::connect(quitButton, SIGNAL(clicked()), this, SLOT(quitPicture())); //working perfectly

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(this);
    layout->addWidget(quitButton);
    window->setLayout(layout);
    window->show();
}

void myClass::quitPicture()
{
    std::cout << "calling quitPicture" << std::endl;
    QApplication::quit();
}

Upvotes: 6

Views: 21558

Answers (3)

user6892219
user6892219

Reputation:

void my_exit_func()
{
    // in mainwindow.cpp
    delete MainWindow;
}

Upvotes: 0

kayleeFrye_onDeck
kayleeFrye_onDeck

Reputation: 6958

This answer covers new signal/slot syntax in Qt and also additionally covers how to handle it when using a signal that uses overloads.

For signals with no overloads using QObject as an example object:

QObject obj(nullptr); 

QObject::connect(&obj, &QObject::destroyed, QCoreApplication::instance(), \
 &QCoreApplication::quit);

For signals with overloads using QProcess as an example object:

QProcess * process = new QProcess(QCoreApplication::instance());

QObject::connect(process, static_cast<void (QProcess::*)(int)>(&QProcess::finished), \
                     QCoreApplication::instance(), &QCoreApplication::quit); 

That crazy-looking syntax is basically this, as placeholder syntax:

static_cast< _signalReturnType_( _ObjectName::*_ )( _overloadType1_, _overloadType2_, \
…etc )>( _&ObjectName::signalName_ )

You can check out this link if you want the details on why.

Since QProcess has two overloads, this is the other overload for it:

QProcess * process = new QProcess(QCoreApplication::instance());

QObject::connect(process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>( \
 &QProcess::finished ), QCoreApplication::instance(), &QCoreApplication::quit);

If this crazy-looking stuff is spinning your head, don't sweat it. You can comment questions here, as I usually check SO daily, or at least nowadays.

Upvotes: 0

Daniel V&#233;rit&#233;
Daniel V&#233;rit&#233;

Reputation: 61526

The button's clicked signal can be connected directly to the application's quit slot:

QObject::connect(quitButton, SIGNAL(clicked()),
                 QApplication::instance(), SLOT(quit()));

Upvotes: 13

Related Questions