Qt: How to handle custom events with connect?

半腔热情 提交于 2021-02-11 14:21:45

问题


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:


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



来源:https://stackoverflow.com/questions/27783059/qt-how-to-handle-custom-events-with-connect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!