Call events from the main function

Viewed 128

I was used, in java, to create events almost anywhere, but in c++ (Qt), I notice that you have to create a class to be able to use the object's events. My question is the following : would it be possible to use MouseEvent (or any other event) belonging to a QPushButton from the main function ?

#include <QApplication>
#include <QWidget>
#include <QPushButton>

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

    QWidget window;

    QPushButton* btn = new QPushButton("Add",&window);

    //Here, an event related to 'btn' to update the window...

    window.show();

    return app.exec();
}

PS : I know it's better to use the Qt Designer form, but I'm just asking about the possibility of doing this task.

3 Answers

Some events, e.g. mouse movement or focus changes, are not accessible through slots/signals.

You can use a small proxy QObject to filter events for other objects. See installEventFilter() for a code sample. You don't need to actually filter the events; you may just listen in and let them pass through.

Likewise, you can trigger/fake an event manually through QCoreApplication via notify().

As Joel Bodenmann notes, Qt uses signals and slots. You can have a slot on a QObject, but Qt can also connect to a lambda. Your lambda would have to capture window by reference, so it can update the window.

You'd probably want to connect the clicked event.

Qt offers the signal & slots mechanism. You can simply connect the QPushButton::clicked() signal to a slot that then performs the update you're referring to.

Using C++11's lambda:

// Create pushbutton
QPushButton* btn = nw QPushButton("Add",&window);

// Connect slot to 'clicked' signal
QObject::connect(btn, &QPushButton::clicked, []{
    qDebug("Button clicked!");
    // ... whatever else you want to happen on a button click
});

Keep in mind that you have other problems in your code as pointed out in the comments.

Related