简体   繁体   English

从主函数调用事件

[英]Call events from the main function

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.在 java 中,我几乎在任何地方创建事件,但是在 c++ ( Qt ) 中,我注意到您必须创建一个类才能使用对象的事件。 My question is the following : would it be possible to use MouseEvent (or any other event) belonging to a QPushButton from the main function ?我的问题如下:是否可以从主函数使用属于QPushButton MouseEvent (或任何其他事件)?

#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. PS:我知道最好使用 Qt Designer 表单,但我只是询问是否可以执行此任务。

Some events, eg mouse movement or focus changes, are not accessible through slots/signals.某些事件,例如鼠标移动或焦点更改,无法通过插槽/信号访问。

You can use a small proxy QObject to filter events for other objects.您可以使用一个小的代理 QObject 来过滤其他对象的事件。 See installEventFilter() for a code sample.有关代码示例,请参阅installEventFilter() 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() .同样,您可以通过QCoreApplication通过notify()手动触发/伪造事件。

As Joel Bodenmann notes, Qt uses signals and slots.正如 Joel Bodenmann 所说,Qt 使用信号和槽。 You can have a slot on a QObject , but Qt can also connect to a lambda.您可以在QObject上有一个插槽,但 Qt 也可以连接到 lambda。 Your lambda would have to capture window by reference, so it can update the window.您的 lambda 必须通过引用捕获window ,以便它可以更新窗口。

You'd probably want to connect the clicked event.您可能想要连接clicked事件。

Qt offers the signal & slots mechanism. Qt 提供了信号和插槽机制。 You can simply connect the QPushButton::clicked() signal to a slot that then performs the update you're referring to.您可以简单地将QPushButton::clicked()信号连接到一个插槽,然后执行您所指的更新。

Using C++11's lambda:使用 C++11 的 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.请记住,正如注释中指出的那样,您的代码中还有其他问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM