在 Qt 中等待按钮按下

发布于 2024-11-30 03:15:52 字数 215 浏览 1 评论 0原文

我有一个继承自QDialog的自定义类。我正在使用函数 foo 创建此对话框,并且 foo 仅在按下对话框中的某个按钮时才继续执行其操作。我正在考虑使用信号和插槽,但是如何让 foo 响应来自另一个线程的信号呢?

编辑:基本上我想知道如何使用我自己的对话框重新实现 QInputDialog::getText() 的功能。

I have a custom class inheriting from QDialog. I'm creating this dialog with function foo, and foo would like to continue doing its thing only when a certain button in the dialog is pressed. I was thinking of using signals and slots, but then how could I get foo to respond to a signal from another thread?

EDIT: basically I want to know how to reimplement the functionality of QInputDialog::getText() using my own dialog.

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

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

发布评论

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

评论(2

雾里花 2024-12-07 03:15:52

您的 foo() 函数可以在 [QWaitCondition][1] 对象上调用 wait(),然后您的按钮可以在同一对象上调用wakeOne() 以导致 wait() 返回。

也就是说,实际上没有必要使用多线程来重新实现 QInputDialog::getText()。您应该能够在单个线程内重新实现该功能,而不会出现任何问题,并且这样做会更简单、更可靠。

(注意:假设您希望 getText() 版本阻塞并且直到按下按钮后才返回,您需要调用 QDialog::exec()。不过,我不推荐这种编程风格,因为它是容易出错...例如,如果用户在 QInputDialog 仍然打开的情况下关闭 QInputDialog 的父窗口,会发生什么情况? QInputDialog 的“this”指针现在是一个悬空指针,使所有内容都基于事件(即仅信号和槽)更干净、更安全,而不是尝试在您自己的代码中阻止或递归 Qt 的事件循环)。

Your foo() function could call wait() on a [QWaitCondition][1] object, then your button could call wakeOne() on the same object to cause the wait() to return.

That said, there is really no necessity for using multithreading to reimplement QInputDialog::getText(). You should be able to reimplement that functionality inside a single thread without any problems, and doing it that way will be much simpler and more reliable.

(Note: assuming you want your version of getText() to block and not return until after a button is pressed, you'll need to call QDialog::exec(). I don't recommend that style of programming though, as it's error-prone... for example, what happens if the user closes your QInputDialog's parent window while the QInputDialog is still open? That deletes the QInputDialog object whose getText() method the program is still blocked inside, likely causing a crash because the QInputDialog's "this" pointer is now a dangling pointer. It's much cleaner and safer to make everything event-based instead (i.e. signals and slots only), and not attempt to block or recurse Qt's event loop in your own code)

轻拂→两袖风尘 2024-12-07 03:15:52

http://doc.qt.io/qt-4.8/qdialog.html #modal-dialogs

模态对话框将阻止用户与其他窗口交互,这听起来像是您需要的。另外,我认为你想调用 exec() 而不是 show()。 Show() 立即将执行返回给调用者,而 exec() 会阻塞。

http://doc.qt.io/qt-4.8/qdialog.html#modal-dialogs

Modal dialogs will block the user from interacting with other windows, which it sounds like you will need. Also, I think you want to call exec() instead of show(). Show() returns execution to the caller immediately, where as exec() blocks.

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