How do I build a graphical user interface in C++?


Question

All of my C++ programs so far have been using the command line interface and the only other language I have experience with is PHP which doesn't support GUIs.

Where do I start with graphical user interface programming in C++? How do I create one?

1
238
7/5/2019 12:02:42 PM

Accepted Answer

Essentially an operating system's windowing system exposes some API calls that you can perform to do jobs like create a window, or put a button on the window. Basically you get a suite of header files and you can call functions in those imported libraries, just like you'd do with stdlib and printf.

Each operating system comes with it's own GUI toolkit, suite of header files, and API calls, and their own way of doing things. There are also cross platform toolkits like gtk, qt, and wx widgets that help you build programs that work anywhere. They achieve this by having the same API calls on each platform, but a different implementation for those API functions that call down to the native OS API calls.

One thing they'll all have in common, which will be different from a CLI program, is something called an event loop. The basic idea there is somewhat complicated, and difficult to compress, but in essence it means that not a hell of a lot is going in in your main class/main function, except:

  • check the event queue if there's any new events
  • if there is, dispatch those events to appropriate handlers
  • when you're done, yield control back to the operating system (usually with some kind of special "sleep" or "select" or "yield" function call)
  • then the yield function will return when the operating system is done, and you have another go around the loop.

There are plenty of resources about event based programming. If you have any experience with javascript, it's the same basic idea, except that you, the scripter have no access or control over the event loop itself, or what events there are, your only job is to write and register handlers.

You should keep in mind that GUI programming is incredibly complicated and difficult, in general. If you have the option, it's actually much easier to just integrate an embedded webserver into your program and have an html/web based interface. The one exception that I've encountered is Apple's cocoa+xcode+interface builder + tutorials that make it easily the most approachable environment for people new to GUI programming that I've seen.

140
1/14/2017 1:07:54 PM

There are plenty of free portable GUI libraries, each with its own strengths and weaknesses:

Especially Qt has nice tutorials and tools which help you getting started. Enjoy!

Note, however, that you should avoid platform specific functionality such as the Win32 API or MFC. That ties you unnecessarily on a specific platform with almost no benefits.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon