0
votes

Here is a "hello world" button that display a window and button. I would like to do a cout or any other custom functionality when the button is clicked but I'm stuck.

   #include <QApplication>
   #include <QPushButton>
   #include <iostream>

   int main(int argc, char **argv){
        // create app
        QApplication app (argc, argv);

        // create window
        QWidget window;
        window.setWindowTitle("MyWindow");
        window.setFixedSize(600, 480);

        // create button
        QPushButton *button = new QPushButton(&window);
        button->setGeometry(10, 10, 100, 35);
        button->setText("hello!");

        // event handling
        // HERE IS THE PROBLEM
        QObject::connect(button, SIGNAL(clicked()), ???, SLOT(???));

        // show window
        window.show();

    }

How can I append a custom function to the SLOT? So I can console log stuff and handle the event on my own way? I can connect it to a QMediaPlayer for example to start/stop but I'm still very confused on how to use the signal/slot.

1

1 Answers

1
votes

You need do all this things inside QObject subclass, or you can use new syntax of signal and slot and in this case you will be able to do this in main() function, use lambdas and so on. But it can be done only in Qt5.

QObject::connect(button, &QPushButton::clicked, someFunction);

If you want do this with old syntax then you need create some subclass and then create custom slots. The most common example you can find here: http://qt-project.org/doc/qt-4.8/mainwindows-application.html