Qt:如何使用connect处理自定义事件? [英] Qt: How to handle custom events with connect?

查看:105
本文介绍了Qt:如何使用connect处理自定义事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是显示窗口和按钮的"hello world"按钮.我想在单击按钮但被卡住时执行 cout 或任何其他自定义功能.

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();

    }

如何将自定义函数附加到SLOT?这样我就可以控制台日志内容并以自己的方式处理事件了吗?我可以将它连接到QMediaPlayer以启动/停止,例如,但是我仍然对如何使用信号/插槽感到困惑.

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.

推荐答案

您需要在QObject子类中执行所有这些操作,或者可以使用signal和slot的新语法,在这种情况下,您可以在main中执行此操作()函数,使用lambdas等.但这只能在Qt5中完成.

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);

如果要使用旧语法执行此操作,则需要创建一些子类,然后创建自定义插槽.您可以在这里找到最常见的示例: http://qt-project.org/doc/qt-4.8/mainwindows-application.html

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

这篇关于Qt:如何使用connect处理自定义事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆