Search code examples
c++qtqt4signals-slots

connecting slots outside mainwindow class


I have some GUI ( showing the bill in using QTableWidget ) which I have implemented outside the MainWindow class in my checkout.cpp file. I am having trouble in connecting slots inside the checkout.cpp. Since the MainWindow class inherits from the QMainWindow, I can associate the appropriate slot function with the this object.

How do I do this in the CheckOut class which does not inherit from QMainWindow or QWidget?

EDIT(CODE):

CheckOut::CheckOut(string token)The CheckOut class does not inherit any other class. I am getting error: /home/sudeep/Desktop/mesonero project/mesonero-build-desktop-Qt_4_8_1_in_PATH__System__Release/../mesonero/management.cpp:29: error: no matching function for call to 'QObject::connect(QPushButton*&, const char [11], Management* const, const char [8])'
{   CustomerToken = token;
   if(!findCustomer())
       QMessageBox::critical(0,QObject::tr("Check Out"),"Invalid Customer Token");
   else{
           generateBill();
           provideDiscount();
           QPushButton *payButton = new QPushButton("Pay");
           QObject::connect(payButton,SIGNAL(clicked()),this,SLOT(deleteCustomer()));
           CustomerBill->layout()->addWidget(payButton);
       }
}

void CheckOut::deleteCustomer()
{
       DatabaseManager *dbm = DatabaseManager::Instance();

       QSqlQuery query("DELETE FROM `Residing_Customer` WHERE Customer_Token = '"+QString::fromStdString(CustomerToken)+"'",dbm->db);
       query.exec();
       CustomerBill->close();
}

EDIT(ERROR):

/home/sudeep/Desktop/mesonero project/mesonero-build-desktop-Qt_4_8_1_in_PATH__System__Release/../mesonero/checkout.cpp:29: error: no matching function for call to 'QObject::connect(QPushButton*&, const char [11], CheckOut* const, const char [8])'


Solution

  • When you want to use slots and signals you need to add Q_OBJECT in the private part of the class and inherits from QObject.

    Any Qt class that you can use inherits from QObject, therefore if you are inheriting from a QWidget you are also inheriting from QObject.

    class CheckOut : public QObject {
    Q_OBJECT
    ...
    }
    

    If you are passing a QObject* parent to your CheckOut constructor you may want to build the QObject subobject with that parent as well:

    CheckOut::CheckOut(QObject* parent) : QObject(parent) { ... }