gpt4 book ai didi

c++ - Qt:如何使用连接处理自定义事件?

转载 作者:行者123 更新时间:2023-11-28 06:29:56 25 4
gpt4 key购买 nike

这是一个显示窗口和按钮的“hello world”按钮。我想在单击按钮时执行 cout 或任何其他自定义功能,但我被卡住了。

   #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 以启动/停止,但我仍然对如何使用信号/插槽感到困惑。

最佳答案

你需要在 QObject 子类中做所有这些事情,或者你可以使用信号和槽的新语法,在这种情况下你将能够在 main() 函数中做这些,使用 lambdas 等等。但它只能在 Qt5 中完成。

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

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

关于c++ - Qt:如何使用连接处理自定义事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27783059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com