Eejin Eejin - 1 month ago 23
C++ Question

Qt Slot function not invoked

I cannot for the live of me figure out why my function isn't called correctly after connecting it.

.h file

class NewCustomer : public QObject {
Q_OBJECT

public:
QWidget* newCustomer = new QWidget;
QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);

NewCustomer(QObject *parent);
~NewCustomer();

private slots:
void aAccepted();
};


.cpp file

void thisfunctionworksthough() {
QMessageBox msgBox;
msgBox.setText("The document has been modified.");
msgBox.exec();
}

NewCustomer::NewCustomer(QObject *parent) : QObject(parent) {
connect(this->buttonBox, &QDialogButtonBox::accepted, this, &NewCustomer::aAccepted);
connect(buttonBox, &QDialogButtonBox::rejected, thisfunctionworksthough);
newCustomer->setMinimumSize(700, 600);
newCustomer->show();
}

void NewCustomer::aAccepted() {
QMessageBox msgBox;
msgBox.setText("The document has been modified.");
msgBox.exec();
}


The free function works but the one inside the class defined as slot doesn't. Why?

Answer

It was very stupid of me, but apparently I created the class instance by value so it got deleted when the scope ended. I made sure that it won't get freed from memory so quickly and now it works like a charm.