开发者

How to make a simple non-blocking popup window in a console C++ program?

开发者 https://www.devze.com 2023-02-13 01:20 出处:网络
I try to figure out in which C++ GUI toolkit (+stdlib+libc) it would be easiest to implement such a useful function in a normal command-line application:

I try to figure out in which C++ GUI toolkit (+stdlib+libc) it would be easiest to implement such a useful function in a normal command-line application:

void ShowStringWindow(string& s) {
  // ...
}

ShowStringWindow should display a window with an editable box containing string s.

It should return immediately, so the main thread can continue.

Notes:

  • If the main thread changes the string the displayed, string should change as well. (active checking is fine)
  • If a user edits the string (and confirms with enter) the string s should be updated.
  • You can assume that the main thread will not read or write to this string at the time of the update.
  • Next calls to ShowStringWindow add more similar windows (or more widgets to existing window开发者_开发知识库 if that is not-too-difficult to implement).
  • It should work on linux/ubuntu.

I would be very grateful for a working code, but that is not necessary to be useful.


To do this with Qt, you need to:

  • Create a mutex for the string variable.
  • Create a thread, obviously.
  • Create a QApplication object, in that thread. (on the first call)
  • Set the "setQuitOnLastWindowsClosed" to false on the QApplication. (on the first call)
  • Create the dialog and "exec" it.

After the "exec" function returns, you need to:

  • Delete the dialog object
  • Call QApplication::instance()->quit();
  • Delete the QApplication object.
  • End the thread.

There are a few ways you can update data from the main thread.
One way would be to use signals/slots with queued connection type. Using this, the UI thread updates the value. Easing the impact on the main thread. However, note that if the value update rate is too high, like 2000 times per second, you might want to change to polling the value. To do that, you might find QTimer helpful.

Updating data to the main thread should be somewhat easier, just lock the mutex and insert the value. At this point, you could check if the value that we previously got from the main thread is still the current value in the main thread. You did state that it doesn't change, but i'd not trust that :)

I hope this is sufficient. We used this to create a Qt based error dialog for a console program.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号