QT 应用程序的代码应该放在哪里?

发布于 2024-09-06 20:30:36 字数 341 浏览 2 评论 0原文

我从 QT4 开始,我想知道在哪里放置我的应用程序代码。
这里?

void MainWindow::changeEvent(QEvent *e) {...}

还是这里? (具体在哪里?)

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

如果我希望我的应用程序不仅对用户事件做出反应,而且定期循环执行,我应该将循环放在哪里?

I'm starting with QT4, I'm wondering where to put my application code.
Here?

void MainWindow::changeEvent(QEvent *e) {...}

Or here? (where exactly?)

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

If I want my app not only react to user events, but to execute regularly on a loop, where do I put the loop?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千仐 2024-09-13 20:30:36

除非您在非 gui 线程中循环,否则您将通过循环(在隐式主 gui 线程中)阻塞 GUI。这里有几种不同的方法:

  1. 使用线程。 Qt 的信号和槽是线程安全的。因此,在线程中,您可以调用模拟器(可能会阻塞),然后模拟器会将数据返回到调用线程。然后,您可以向 GUI 线程发出信号,该线程将响应该信号并相应地更新 GUI。
  2. 使用计时器。您可以使用 QTimer (或 singleShot 计时器)设置为零毫秒的延迟。这会在不阻塞循环的情况下尽可能频繁地调用您的槽。如果插槽快速返回,则不会出现阻塞 GUI 的情况,并且会稍微简化编程。

还有其他不同的方法,例如使用 processEvents() 但我个人推荐线程方法。

Unless you loop within a non-gui thread, you will block the GUI by looping (in the implicit main gui thread). Here's a couple of different approaches:

  1. Use threads. Qt's signals and slots are thread safe. Thus, within a thread you can call your emulator (which may block) and which will then return data to the calling thread. You can then emit a signal to the GUI thread which will respond to the signal and update the GUI accordingly.
  2. Use a timer. You can use QTimer (or a singleShot timer) set to a delay of zero milliseconds. This has the affect of calling your slot as often as it possibly can while not blocking the loop. If the slot returns quickly this will not appear to block the GUI and simplifies programming a little bit.

There are other different approaches, such as using processEvents() but I'd personally recommend the threads approach.

无人问我粥可暖 2024-09-13 20:30:36

Qt 有自己的主循环,您可以使用 QTimer 类连接到它。

如果您想提供自己的事件循环,可以使用 QApplication::processEvents( )向 Qt 发送信号以处理其事件(并保持负责任的 UI)。

另外, QAbstractEventDispatcher 可能对您有用。

这个问题可能也有用。

Qt has its own main loop, you can connect to it using the QTimer class.

If you want to provide your own event loop, you can use QApplication::processEvents() to signal Qt to process it's events (and keep a responsible UI).

Also, QAbstractEventDispatcher might be useful to you.

This question might also be useful.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文