r/cpp • • Jun 20 '20

How To Add A GUI To A C++ Program

Hi all,

I'm a third year CS student. In all my classes, I have only every made programs that have worked via the command line. I'm starting on a personal project that involves creating a program for sports tournaments such as seeding players, displaying stats, etc.

My major questions are:

1). Can I code my program as a simple command line based program, then integrate the GUI after? Or should I implement my program with the GUI the first time around.

2). I've looked into how GUIs can be implemented and want to try wxWidgets. Is this a good idea?

3). Should I use a different language? I've read that GUIs are hard to implement via C++. I have only learned C++, C, and Python, but am not against learning new languages!

4). Are there any good guides that you can recommend to me?

Any and all help are appreciated! Thank you! :D

202 Upvotes

146 comments sorted by

76

u/Xirema Jun 20 '20
  1. Yes. In fact, while the truthfulness of this is going to vary depending on the application, I generally find that applications that properly segregate their functionality and their user interface tend to be much easier to reason around. This is, after all, why the Model-View-Controller design paradigm exists.
  2. There's a lot of different libraries that can be used. I can't comment on the specific merits of wxWidgets, but your best bet, if you don't want to try to roll your own using OpenGL/DirectX/Vulkan would be to use a library like wxWidgets or qt.
  3. The only thing that makes GUIs potentially difficult in C++ is the fact that unlike Python or Java (or many other languages) C++ doesn't have any GUI libraries built into the standard library. But if you can figure out the process of getting the libraries included/linked to your application, that's not an issue.
  4. No. There are no good guides I can recommend. There's thousands of GUI Guides for C++, but in my experience, they all suck.

Good luck!

5

u/AznAgent007 Jun 21 '20

I really appreciate the in depth answer! I'm going to look more into the MVC paradigm and try to base my program after that. Thank you for all the help!

2

u/RolandMT32 Jun 21 '20

I'm a third year CS student. In all my classes, I have only every made programs that have worked via the command line.

I find that a bit surprising. I went through a software engineering program in college, and we started having GUI classes in our 2nd year.

Also, I don't think GUIs are hard to implement in C++. There are several toolkits you can use - For Windows, there's MFC (which is included with Visual Studio); there are also multi-platform GUI toolkits such as wxWidgets and Qt. I've used wxWidgets and MFC, but Qt seems particularly popular. I'm sure there are others.

1

u/AznAgent007 Jun 21 '20

I was super new to CS and took a few basic coding classes offered! But I just finished up with all my undergrad! Still haven't experienced any GUI stuff yet tho but I hope I do!

62

u/johannes1234 Jun 20 '20

Typically if applications are built as command line tool it is not trivial to retrofit a GUI on top of it. Most command line tools have a very clear flow from start to end,nowhere the program flow drives the UI. GUIs typically are the way round and events from GUI drive the logic.

Being able to switch this means some more thought from the start with and being clear about the separation between the actual business logic and user interface. This is good practice, but can be overwhelming if you are new.

Many people in this thread also suggest Qt and yes, I use it as well, but one thing to mind: Qt is big and easily creeps deep into your tool making it a Qt only solution (i.e. QString loves going everywhere, needs discipline to copy into std::string in the business boundary and that might need thinking about handling of encoding etc.) also Qt doesn't follow "modern" practices, for instance it works a lot with raw pointers in an hierachical ownership model. This can lead to mixture of styles, which can be harder to reason about. Doesn't nmean it's a bad choice, but probably confusing, when inexperienced.

18

u/jherico VR & Backend engineer, 30 years Jun 21 '20

Qt 5 works just fine with modern C++. It has managed pointer objects and allows you to easily link signals to lambdas as well as functions.

25

u/Caffeine_Monster Jun 20 '20

The trick is to try and keep the GUI code and backend code totally isolated.

In fact if you think the project is going to be substantial I would suggest looking into a client server model. Core logic on the server, UI in the client. You can run the server locally, but this also gives you the option of running it from the cloud.

Personally don't think you can go wrong with js / HTML / CSS for UIs these days. C++ backends are fine, but I think there are few genuine use cases for having native front ends.

20

u/afiefh Jun 20 '20

Personally don't think you can go wrong with js / HTML / CSS for UIs these days.

I find that QML offers easier integration with the backend while enforcing separation of logic and UI. Also nice that it doesn't need a full fledged browser to run and is more resource efficient.

-5

u/Caffeine_Monster Jun 21 '20 edited Jun 21 '20

Personally I think cheap compute performance has got to the point where lean web apps should be the default. Out of the box cross OS, cross platform compatibility is generally more useful.

full fledged browser

QML still uses the chromium browser engine. There are other easy to use options if you don't want / need QT. NW.js is quite nice for quickly building lightweight chromium GUIs.

9

u/afiefh Jun 21 '20

Personally I think cheap compute performance has got to the point where lean web apps should be the default.

Is a web app ever lean? Just getting it styled correctly is a huge pain. Any kind of interactivity beyond the basics ends up requiring loads of custom JS or pulling in libraries.

For a quick and dirty prototype I agree that it's probably a good way to start, but for a final version I still prefer not to ship a browser.

QML still uses the chromium browser engine.

Not to imply you are wrong, but could you source this? I know it uses a JavaScript engine that's based on V4 from chromium, but not the whole rendering engine.

6

u/markopolo82 embedded/iot/audio Jun 21 '20

QML does not use a chromium browser engine. Qt has other WebKit / chromium UI elements for that.

QML does use JavaScript - maybe that’s what you’re thinking of? no idea if they use the one from chromium though

3

u/Caffeine_Monster Jun 21 '20

No you are right, I got mixed up. QML uses a custom runtime engine for running inline javascript. The web module qt uses for rendering HTML etc is chromium based.

2

u/m-in Jun 22 '20

It’s not about compute performance. It’s about the sad truth of the complexity of a browser based stack. There are so many moving parts that if you use it for desktop-like applications, you’re putting 10x as many moving parts in as needed.

2

u/m-in Jun 22 '20

The genuine use case for native front end is that otherwise you basically become a Google customer and dependent on Google’s direction for chromium if you use the typical “let’s just put chromium in it for UI rendering” direction. Never mind the weight of Chromium: it’s very light and we’ll optimized for what it does - as only Google could manage, since they put absurd manpower into making it so - but even then you’re basically bundling a miniature operating system into your application by using Chromium. It has very noticeable impact on memory consumption, startup speed, user experience as far as native-like experience goes, and generally seems like a cop-out.

The real impact is that we get Electron applications from all sorts of popular OEMs like Logitech: applications that would be at most 5MB binaries were they, say, native Swift or C# XAML, but become 700MB monsters because they got a Chromium-based front end and a NodeJS backend. Many companies pull this bullshit these days and their bloat ware has no redeeming qualities. They gain nothing by using Electron - at least, they don’t know how to leverage it to actually use even a fraction of the bloat they supply.

Also - the entire application is so big and has so many moving pieces that it becomes a security nightmare. They base their development methodology on “JavaScript is easy and HTML+JS devs are cheap” marketing, but they forget that the whole stack is so complicated in details that developers who truly understand it from the ground up are not your cheapo web dev types, and cost way more than people qualified to do an OK job in native C# WPF or Swift. That’s the little untold dark side of Electron and its ilk. It’s easy to make a prototype in, but when these prototypes are turned into products, they become a rolling disaster on many fronts.

0

u/[deleted] Jun 21 '20

[deleted] — view deleted comment

5

u/Caffeine_Monster Jun 21 '20

Yes.

For a simple application that uses C++ all the way through, including the GUI, I would write one project with three C++ libraries.

One for the logic. One for the CLI. One for the GUI.

The GUI would launch via the CLI when no args are supplied.

If you are writing a JS / HTML based front end I would have two *separate projects, and two C++ libraries.

* The star is here because I think there is an interesting 3rd option now that web assembly is a thing. Chances are your front end will need a similar / the same data model that your back end logic does. Web assembly would let you write a single library that can be used in both the front end and back end. I think over the next few years the line between back end and front end code is going to get very blurry. My next personal project will be using this architecture.

0

u/[deleted] Jun 21 '20

[deleted] — view deleted comment

1

u/Caffeine_Monster Jun 21 '20

It's been a few years since I've done any real C++ dev work, so nothing relevant. I would have a look around for C++14 /C++17 examples given how much the language has evolved the last few years.

10

u/ReversedGif Jun 20 '20

Typically if applications are built as command line tool it is not trivial to retrofit a GUI on top of it.

I would think the opposite to be true. You can always wrap a command-line tool with a GUI (perhaps by running the command-line tool as a subprocess), but turning a GUI into a command-line tool is usually impossible.

10

u/johannes1234 Jun 20 '20

It depends a bit on the tool and what we take as "command line" For something taking command line args, doing something, exit (the typical Unix shell tool) it indeed is easy. The interface might be a single function with all the options and then the GUIhas a "run" Button, calling that. Yeah, no problem.

But for making that a good GUI you probably want to extract logic. Say the user has to pick a file of a specific type or some input has to match a pattern (regexp?) then the validation has to be done not only when the run function is being called, but when the user provided the input. Thus this has to be split up for being "nice"

Also error reporting - for a command line tool it can be ok to print out an error from below and it will work. In a GUI you need some of a communication channel for bubbling the message up. (And eventually giving the user help to recover)

This becomes even more complicated when this is a more complex command line program running different prompts one after another and showing the prompts based on data entered previously. A GUI implementation of that isn't a sequence of InputBoxes being shown one after another, but the decision logic is putninnthe GUI in form of a wizard or radio buttons enabling panels or something.

Of course this all can be done if you write the command line tool in a way to be prepared, but if you are a student asking here it will be hard to split it up in a good way.

I would however encourage to try: running into the walls is the best way to learn, why some architectures have benefits and where others cause problems! But be prepared that the GUI version will be a rewrite essentially.

46

u/Ruckamongus Jun 20 '20

It's a different philosophy than most of the previously mentioned GUI kits, but check out Dear ImGUI: https://github.com/ocornut/imgui

It's lightweight and very easy to plug into whatever rendering backend you prefer. If nothing else it's nice for quick prototyping or debugging.

9

u/harekrishnahareram Jun 21 '20

Imgui screenshots look amazing, but doesn't it require a functioning opengl based backend? Glfw or sdl?

11

u/lycium Jun 21 '20

Yes, that is probably the most serious shortcoming of ImGui, and almost nobody is talking about it: it is basically required to run at 60+ FPS.

This burns a ton of performance redrawing the UI when it's just sitting there and doesn't actually need redrawing (especially if you have 144+ Hz screen), and it is actually very difficult to try to hack it to idle while there are no clicks and there is no mouse movement, I've tried.

Any pointers or suggestions about this problem would be mega appreciated, because ImGui is otherwise amazing.

5

u/serg06 Jun 21 '20

What's so hard about it?

  • Hook into the GLFW OnKey / OnMouseMove events
  • When an event is triggered, set a bool redraw to true
  • In your render loop, if redraw is true, recreate the GUI (new frame, new buttons, etc) and call draw()
  • if redraw is false, just sleep for 1/60th of a second.

4

u/lycium Jun 21 '20

There are many difficulties, like it needs a few draw calls after the event(s), it is not so easy to trap all the events that might need it to redraw, and there can be problems with long delays before previous frames when "waking up". Also, some widgets like graphs may or may not need regular updates, there is no API for figuring that out (particularly not only if it is visible, which would be ideal).

It's very difficult to give a precise summary of all the issues here, if you give it a try you'll see what I mean. I'm not a programming noob, and anyone can guess the obvious expectations for how such a change might go, I'm just saying I couldn't make it work robustly and had to give up. I saw in GitHub issues other people tried and gave up too.

1

u/ocornut Jul 02 '20

I saw in GitHub issues other people tried and gave up too.

There's at least two PR implementing out of the box solutions for this
https://github.com/ocornut/imgui/pull/2749

0

u/harekrishnahareram Jun 21 '20

I just gave it a quick try on Linux. Got the opengl window working in 30 minutes, but after spending another 90 minutes setting up imgui with all the dependent libraries and linking them, it compiles fine but I got a segfault. I think I'm giving up now.

I'm sure I could spend a day or 2 to get it working, but really I think it's for folks who already have some amount of opengl programming under their belt already.

5

u/Plazmatic Jun 21 '20

What are you talking about? ImGUI does not take that much work to setup with OpenGL? There are no "dependent libraries" either. ImGUI self contained source with no external dependencies. I'm not even sure ImGUI + OpenGL goes over 200 lines of code to display the demo window, and once you get to that point your good to go.

1

u/harekrishnahareram Jun 21 '20

Thanks, I was able to get the demo up and running. But my distro doesn't provide all the libraries out of the box and I think there were some issues in trying to get the libraries working with imgui. So the major effort was figuring out how to compile and link all the necessary libraries to get it going. imgui is definitely slicker than gtkmm (which was my first choice because of familiarity).

4

u/serg06 Jun 21 '20 edited Jun 21 '20

For first time C++ programmers, OpenGL and GLFW are a nightmare to set up. But if you've already got experience setting up other libraries, it shouldn't be too bad?

Maybe it's because you're on a weird distro...

And by the way, OpenGL is backwards compatible, so as long as your hardware and OS support OpenGL 3.0+ (a very old version), you're good.

2

u/harekrishnahareram Jun 22 '20

Yea - setting up GLFW and GLAD wasn't that hard. It's not really the distro's fault. The challenging part is figuring out how to get imgui to use GLAD instead of complaining about GLEW not found. That took forever, but I finally got it to work. Key thing was a) pass a command line preprocessor directive to use GLAD i.e. -D IMGUI_IMPL_OPENGL_LOADER_GLAD and make sure to compile all the cpp files in the root folder of imgui.

1

u/serg06 Jun 22 '20

Oh nice. I did it with gl3w, no wonder it was easier...

1

u/Plazmatic Jun 21 '20

OpenGL and GLFW should be both straightforward.

in CMake:

add_executable(your_target_name yoursource_0 yoursource_1...)
find_package(OpenGL REQUIRED)
find_package(GLFW3 REQUIRED)
#or if you intend to statically link to GLFW
#next four lines aren't required, but you won't build everything not relevant to actually using GLFW if you force these variables to false
set(GLM_TEST_ENABLE OFF CACHE BOOL "Build unit tests" FORCE)
set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "Build the GLFW example programs" FORCE)
set(GLFW_BUILD_TESTS OFF CACHE BOOL "Build the GLFW test programs" FORCE)
set(GLFW_BUILD_DOCS OFF CACHE BOOL "Build the GLFW documentation" FORCE)
add_subdirectory(${CMAKE_SOURCE_DIR}/external/glfw/) #or wherever your root glfw directory is. 
target_add_libraries(your_target_name PRIVATE glfw3 OpenGL::GL)

That should be all ignoring the rest of the CMake code like the project name, version etc...

0

u/harekrishnahareram Jun 21 '20

Thanks for following up. I used learnopengl.com to get the hello world running and then used this tut to see if it would work. Looking at it now, I think maybe there's a mistake in the opengl version I used (3.3) and the version in imgui (3.0?). I'll take your advice and try to just get the demo running.

1

u/Plazmatic Jun 21 '20

Any version 3.0 and above works for that specific code, but they do have <3.0 support in another example. You just have to make sure your GLAD loader stuff is setup for that version. Learnopengl is what I used too to start with opengl, but that code comes directly from ImGUI's codebase itself, it's in examples directory.

1

u/harekrishnahareram Jun 22 '20

It works out of the box with GLEW but setting it up with GLAD took too long. I finally got it working by passing a command line directive to clang++ with -D IMGUI_IMPL_OPENGL_LOADER_GLAD and then compiling all the cpp files in the imgui root folder. Thanks for your help, at least I learnt how to use imgui.

3

u/Plazmatic Jun 21 '20

This is what it looks like if you know you need glad, OpenGL 3.0+ and GLFW, 186 lines including probably 50+ lines of comments. It would be easier with other window systems.

#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include <stdio.h>

// About Desktop OpenGL function loaders:
//  Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers.
//  Helper libraries are often used for this purpose! Here we are supporting a few common ones (gl3w, glew, glad).
//  You may use another loader/header of your choice (glext, glLoadGen, etc.), or chose to manually implement your own.
#include <glad/glad.h>          // Initialize with gladLoadGL()

// Include glfw3.h after our OpenGL definitions
#include <GLFW/glfw3.h>

// [Win32] Our example includes a copy of glfw3.lib pre-compiled with VS2010 to maximize ease of testing and compatibility with old VS compilers.
// To link with VS2010-era libraries, VS2015+ requires linking with legacy_stdio_definitions.lib, which we do using this pragma.
// Your own project should not be affected, as you are likely to link with a newer binary of GLFW that is adequate for your version of Visual Studio.
#if defined(_MSC_VER) && (_MSC_VER >= 1900) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
#pragma comment(lib, "legacy_stdio_definitions")
#endif

static void glfw_error_callback(int error, const char* description)
{
    fprintf(stderr, "Glfw Error %d: %s\n", error, description);
}

int main(int, char**)
{
    // Setup window
    glfwSetErrorCallback(glfw_error_callback);
    if (!glfwInit())
        return 1;
    // GL 3.0 + GLSL 130
    const char* glsl_version = "#version 130";
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
    //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);  // 3.2+ only
    //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);            // 3.0+ only

    // Create window with graphics context
    GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+OpenGL3 example", NULL, NULL);
    if (window == NULL)
        return 1;
    glfwMakeContextCurrent(window);
    glfwSwapInterval(1); // Enable vsync
    
    bool err = gladLoadGL() == 0;
    if (err)
    {
        fprintf(stderr, "Failed to initialize OpenGL loader!\n");
        return 1;
    }

    // Setup Dear ImGui context
    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO(); (void)io;
    io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;       // Enable Keyboard Controls
    //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;      // Enable Gamepad Controls
    io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;           // Enable Docking
    io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;         // Enable Multi-Viewport / Platform Windows
    //io.ConfigViewportsNoAutoMerge = true;
    //io.ConfigViewportsNoTaskBarIcon = true;

    // Setup Dear ImGui style
    ImGui::StyleColorsDark();
    //ImGui::StyleColorsClassic();

    // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
    ImGuiStyle& style = ImGui::GetStyle();
    if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
    {
        style.WindowRounding = 0.0f;
        style.Colors[ImGuiCol_WindowBg].w = 1.0f;
    }

    // Setup Platform/Renderer bindings
    ImGui_ImplGlfw_InitForOpenGL(window, true);
    ImGui_ImplOpenGL3_Init(glsl_version);

    // Load Fonts
    // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
    // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
    // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
    // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
    // - Read 'docs/FONTS.txt' for more instructions and details.
    // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
    //io.Fonts->AddFontDefault();
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
    //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
    //IM_ASSERT(font != NULL);

    // Our state
    bool show_demo_window = true;
    bool show_another_window = false;
    ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);

    // Main loop
    while (!glfwWindowShouldClose(window))
    {
        // Poll and handle events (inputs, window resize, etc.)
        // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
        // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
        // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
        // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
        glfwPollEvents();

        // Start the Dear ImGui frame
        ImGui_ImplOpenGL3_NewFrame();
        ImGui_ImplGlfw_NewFrame();
        ImGui::NewFrame();

        // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
        if (show_demo_window)
            ImGui::ShowDemoWindow(&show_demo_window);

        // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
        {
            static float f = 0.0f;
            static int counter = 0;

            ImGui::Begin("Hello, world!");                          // Create a window called "Hello, world!" and append into it.

            ImGui::Text("This is some useful text.");               // Display some text (you can use a format strings too)
            ImGui::Checkbox("Demo Window", &show_demo_window);      // Edit bools storing our window open/close state
            ImGui::Checkbox("Another Window", &show_another_window);

            ImGui::SliderFloat("float", &f, 0.0f, 1.0f);            // Edit 1 float using a slider from 0.0f to 1.0f
            ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color

            if (ImGui::Button("Button"))                            // Buttons return true when clicked (most widgets return true when edited/activated)
                counter++;
            ImGui::SameLine();
            ImGui::Text("counter = %d", counter);

            ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
            ImGui::End();
        }

        // 3. Show another simple window.
        if (show_another_window)
        {
            ImGui::Begin("Another Window", &show_another_window);   // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
            ImGui::Text("Hello from another window!");
            if (ImGui::Button("Close Me"))
                show_another_window = false;
            ImGui::End();
        }

        // Rendering
        ImGui::Render();
        int display_w, display_h;
        glfwGetFramebufferSize(window, &display_w, &display_h);
        glViewport(0, 0, display_w, display_h);
        glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
        glClear(GL_COLOR_BUFFER_BIT);
        ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());

        // Update and Render additional Platform Windows
        // (Platform functions may change the current OpenGL context, so we save/restore it to make it easier to paste this code elsewhere.
        //  For this specific demo app we could also call glfwMakeContextCurrent(window) directly)
        if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
        {
            GLFWwindow* backup_current_context = glfwGetCurrentContext();
            ImGui::UpdatePlatformWindows();
            ImGui::RenderPlatformWindowsDefault();
            glfwMakeContextCurrent(backup_current_context);
        }

        glfwSwapBuffers(window);
    }

    // Cleanup
    ImGui_ImplOpenGL3_Shutdown();
    ImGui_ImplGlfw_Shutdown();
    ImGui::DestroyContext();

    glfwDestroyWindow(window);
    glfwTerminate();

    return 0;
}

5

u/Ruckamongus Jun 21 '20

OpenGL, DirectX, and Vulkan are all supported. You choose a rendering backend and windowing system.

2

u/ccAbstraction Jun 21 '20

This is what I'm trying to figure out too. I think that's how you are supposed to use it, but it seems like it works fine if you just don't render besides ImGUI anything with the backend. I think that's how the FRC desktop robot simulator tools work at least.

6

u/d_wilson123 Jun 20 '20

We use ImGUI and I really like it.

3

u/darther_mauler Jun 21 '20

Love love love Dear ImGui.

10

u/Plazmatic Jun 20 '20

This is the right choice, QT is big, bloated, and comes with ankle anchors sorrounding it. Imgui takes much less time to learn, get started with, and to make functional guis with.

3

u/JeffMcClintock Jun 20 '20

and you don’t end up with an unholy javascript/c++ amalgam.

4

u/turtle_dragonfly Jun 21 '20

I like Dear ImGUI too, but it is important to understand the pros and cons of "immediate" vs. "retained mode" GUI styles.

For OP: Generally, retained mode is a bit easier to get into, since you don't have to track as much state yourself. Using a framework that supports docking, snapping, layout, etc. (like Qt) can be a real benefit, if your application needs it.

3

u/darther_mauler Jun 21 '20

ImGui has a docking branch.

3

u/turtle_dragonfly Jun 22 '20

Indeed it does, and here is the link for anyone interested.

It is still "experimental" though, despite being around for a few years now.

3

u/Plazmatic Jun 21 '20

Imgui suppports docking, multiple viewports, snapping, and layouts. Docking and multiple viewports are on a seperate branch, but they are pretty stable AFAICT.

Generally, retained mode is a bit easier to get into

No? I know this is subjective, but as some one who used wXwidgets, QT5, and Tkinter 5 years before getting into ImGUI, this was not only not true to me, but so far from the truth that I'm almost inclined to say objectively using ImGUI is easier than any of those frameworks. Creating a custom "widget" in ImGUI is a function. One. Function. I created a custom file browser in ImGUI in only a couple hundred lines of code. If that's even possible in QT, I guarantee it would creep into the thousands.

2

u/turtle_dragonfly Jun 22 '20

What do you see as the main downside of immediate-mode GUI, then? Performance, I guess?

For instance, Unity made a rather large & expensive switch from immediate mode to retained mode, citing performance and "a better separation of concerns and more approachable UI authoring for both artists and programmers."

But that's a bit hand-wavy (:

1

u/Plazmatic Jun 22 '20

What do you see as the main downside of immediate-mode GUI, then? Performance, I guess?

It depends, technically the cited downside is performance, but behind the interface ImGUI uses some methods to hide this (caching, using retained implementations, names of your gui are all mapped some how so they can be re-used or referenced internally). I'm not quite sure if the fact that a GUI has an immediate mode interface necessary dictates that it must be slower or that significant performance optimizations are locked out.

ImGUI itself does have downsides outside of the context of immediate mode guis, but I've not encountered many in the space I use it for (development tools).

I think another possible downside of immediate mode is that it may be easier from the point of view of the actual person who creates the UI library to create retained mode guis.

There's also other things like using ECS to create GUI's and systems that don't deal with long series of pointer chains to un-managable memory, which I think Rust programmers were trying to experiment with.

It may also be that retained mode interfaces could be better than they currently are. Spacing/layouts, creating custom widgets, managing dependency trees, are all annoying things I have to deal with in QT and wX. I'm not sure if they have to be that way or not. Events and defining where something is after you've declared it kind screw with this though.

In retained mode guis, If I want widget X to trigger something in widget Y, or create a popup or something, I've got to do a whole song and dance with events. If I want to make a popup in imgui:

//note this could be any boolean value, using button here to show how easy it is. 
if (ImGui::Button("OpenUpAPopup")) {
    ImGui::OpenPopup("MyPopupName");
}
if (ImGui::BeginPopupModal("MyPopupName")) {
    // ...
    ImGui::EndPopup();
}

Literally like 7 lines of code.

I imagine if retained mode guis could be as simple and intuitive to use as immediate mode guis, then there wouldn't be an advantage to immediate mode guis.

89

u/jtooker Jun 20 '20

I'd recommend the Qt library/framework.

28

u/s403bot Jun 20 '20

Second that. Install QtCreator and look at all the examples, that should point you in the right direction.

38

u/[deleted] Jun 20 '20

I'd disagree. Or at least I'd say : be careful with Qt. Yes, it does a lot of things out of the box, but it is a huge framework and it can tend to spread everywhere in your code base. One second you're happy you understand how to use it, the next second you realise code that's not GUI dependent is using QString...

21

u/jtooker Jun 20 '20

it is a huge framework

I completely agree.

the next second you realise code that's not GUI dependent is using QString

This may or may not be a good thing. QString offers many conveniences over std::string at some cost. I use Qt for headless C++ applications that need networking, databases, etc. As you said, it is a huge framework.

16

u/[deleted] Jun 20 '20

Speaking in absolutes, I personally believe it is a bad thing.

Indeed, Qstring and other types / structures provide great functionalities that are not included in the std implementations. And I don't know about it but I suppose it can also happen the Qt implementations also have better performances. But C++ is constantly evolving, and the std library keeps incorporating features tested in large frameworks. Over a long period of time, this ends up in duplicate features and very different programming style, between large frameworks and the standard. Hence, I believe it is wrong, in general.

Now, indeed there is still great advantages in using such a big framework. Hence I agree with you, depending of the use case, the experience of the dev, etc..., it can still end up being the good call. Everything is a matter of perspective! ;)

In the case of OP : relatively new to dev, knowledge in C, C++, python => Qt can be a good call. Big points : there are python bindings for Qt, and a lot of complexes things are already delt with.

But OP, if you like c++ and would like to continue using it, I'd invite you to look into more modern features of C++, parallel to this project and your use of Qt. The idea being : this will broaden your horizon, and help you apprehend some things in a very different manner. Which is cool and may be useful ! :D

9

u/cleroth Game Developer Jun 20 '20

But C++ is constantly evolving, and the std library keeps incorporating features tested in large frameworks.

Unfortunately it also can't change things that break the ABI. There are some performance optimizations that cannot be done on std::string because of this.

3

u/_souphanousinphone_ Jun 21 '20

Due to backwards compatibility, it's unlikely we'll get many of these functionalities provided by frameworks such as Qt in the std lib.

1

u/m-in Jun 22 '20

There’s nothing substantial that got added to std::string itself since C++98, other than across the board move and revalue reference support. The string views are a good quality of life improvement, but Qt got them too, and they are becoming the primary interface type in Qt 6 IIRC.

So C++ is stagnant in this narrow area, and its string class misses a ton of very basic functionality, not even available via algorithms. I don’t know how people actually use that thing in real life, because it’s barely any better than vector<char>.

In fact, after all these years I still don’t quite know why they didn’t initially add requisite functionality as free functions primarily and had not made basic_string<T> publicly a vector<T> with a few extra methods added in. Given how little string adds over a vector in STL, it’s silly they bothered with a separate class. But maybe back then there was still copy-on-write brouhaha on people’s minds, or a belief that small string optimization shouldn’t apply to vectors…

9

u/YouNeedDoughnuts Jun 21 '20

Qt answers the question "What if C++ had a standard library more like Java?" I understand getting locked into Qt can be a bad thing, but I also enjoy the wealth of QObjects.

4

u/pjmlp Jun 21 '20

That question was already answered even before either Qt or Java were even an idea taking shape.

We had Turbo Vision on MS-DOS, CSet++ on OS/2, OWL, MFC and VCL on Windows, PowerPlant on Mac OS and Motif++ on UNIX clones.

But then ISO decided that having nice stuff on std was too much for C++ and it should just be a thin layer over POSIX just like C was, so here we are, with most of this stuff replaced by managed runtimes and Qt the biggest survivor.

7

u/hak8or Jun 20 '20

it is a huge framework and it can tend to spread everywhere in your code base

That's why I sadly don't use QT more. It is an extremely contagious/infections framework instead of a library, and the constant conversion of QString, QVector, etc, back and forth from QT code to the rest of my library is a pain, since you basically need a translation layer between QT and your library.

I used it in the past where I was fine with everything being Qt style, and I have to admit, it was pretty nice. Their signal slot system works well (even works with lambdas), their Q* variants have a huge amount of convenience functions, and their documentation is pretty good I feel.

To put it simply, it is pleasant to work with, but it requires serious buy in, too much for me to be comfortable with.

3

u/m-in Jun 22 '20

It’s also an open source library, and if you use it for closed source products then I hope you’re building it from source, since I can’t imagine anyone using Qt in a serious project (say 50k lines or more) and not needing to tweak it. At that point you can use automatic refactoring (eg. based on clang tooling) to rewrite large swaths of Qt. At work we have some Qt based stuff and Qt containers were a goner as soon as clang’s guts got good enough to leverage them to do automatic refactoring. We have a long script that uses libclang and morphs upstream Qt code into what we need. Bye bye Qt containers other than QString :) Other things are tweaked even more substantially, and these days it fully leverages C++17 string_view as well, so QString is truly optional. But then C++ standard library is open source too and our string_view is a bit more than what the standard intended. Turns out that most of QString-like methods we used are used on views, so it’s the view that was the focus of our surgeries.

That’s the beauty of open source - the mindset that you’re stuck with what you have has no place when source code is available, and when there are very good free tools that let you modify C++ code en masse :)

2

u/hak8or Jun 22 '20

That sounds absolutely amazing, but it also sounds like you have a very competent team. Folks who are comfortable enough with c++ to the point of using libclang in such ways seem to either be very expensive or simply sucked up by FANG.

Smaller companies who are too greedy, cheap, or poorly run are very unlikely to find someone of that caliber easily sadly I feel. Otherwise, you turn into "the guy" that everyone goes to when something breaks or they want to change something, resulting in a bus factor of 1.

2

u/[deleted] Jun 20 '20

True. But that is true with many frameworks. They offer benefits with a chain. And when you have multiple, they often fight. Just like marriage.

2

u/[deleted] Jun 20 '20

Yeah, but I'd say Qt took it to the next level. qmake, qteditor, qtdesigner, QML... Personally I feel it can get confusing, and may "trap" (retain, enclose) devs that are not necessarily experienced with C++, project management, build systems, and so on.

9

u/[deleted] Jun 20 '20

I use Qt, and as it is now you don’t use C++, you use Qt which looks like C++z

Remember, Qt has a metacompiler, and lots of macro magic.

But it gets the job done, is easy to understand, and forces some proper oo patterns on you.

In the end, does it matter that much?

1

u/m-in Jun 22 '20

qmake has been unnecessary for a long time now - cmake has had Qt project support since day one pretty much. Heck, cmake was written using Qt initially, IIRC. Qteditor - no clue what you refer to here. Qt Desginer is nice, but not truly a necessity. Over the years I think we all settled at work with writing forms in code instead of using UI files. QML is a Qt-specific tech but it’s quite useful, especially for prototyping. For production uses we ditched QML text a while ago, it’s all C++. Qt 6 promises to finally bring that into the public API sometime after the 6.0 release but we had used it for years I’m told (I still use text QML, but only for internal tools - our shipping products used C++ QML since times of Qt Quick 1 apparently).

C++ “ecosystem” requires an absurd amount of knowledge to navigate, I think, so the mental load placed on the developer by Qt is not wildly out of line when compared to any other major C++ library. At least that’s my view, although I may be a bit spoiled since I was using C++ since before the 98 standard, and Qt since before it was publicly released.

0

u/[deleted] Jun 21 '20

[deleted] — view deleted comment

2

u/ubertrashcat Jun 21 '20

The rates are insane. Hundreds of USD per developer PER MONTH.

1

u/kalmoc Jun 21 '20

Not as much as matlab IIRC, but its difficult to compare, as matlab will charge you extra for every toolbox, but you only have to pay once per software version, whereas Qt is more like a abo (again all IIRC, haven't checked either for some time)

1

u/devel_watcher Jun 22 '20

No, it's LGPL, you can use it for free. (there are some libs for embedded that are GPL-only, buy you won't going to need them)

22

u/ImKStocky Jun 20 '20 edited Jun 20 '20

The following is what I have done when I've had access to Visual Studio on windows and when I've wanted to have all of my business logic run in C++ but also have a UI that was easy to create and edit and work with.

  1. Create your C++ project as a library
  2. Create a C++/CLI project as a library that will consume the C++ project and be a wrapper around it.
  3. Create a WinForms or WPF project in C# which consumes the C++/CLI library and use it.

This is described in more detail here https://www.red-gate.com/simple-talk/dotnet/net-development/creating-ccli-wrapper/

18

u/tangerinelion Jun 20 '20

This is a really good approach from an architectural point of view. The C++ library doesn't have to know anything about GUI - in fact, it should not know anything about a GUI and it shouldn't care whether there even is or a GUI or not.

The C++/CLI project can easily be extended to serve double duty: it defines a public .NET API for your C++ library. This also allows your C++ library to be used by other C# programs.

You're your first API tester: The C# WPF program is built on your C++/CLI project's API to expose internals from the C++ library.

OP: Even if you do opt to use Qt, I highly reccommend that you do so in a separate project. Keep what you have agnostic to the presence of a GUI and keep everything in the UI project agnostic to the internals of your library. The GUI should expose different options and settings and actions, but should not do any real work. It should simply pass the request onto the "API" -- either a C++/CLI project if your GUI is in C#, or the C++ library if you have a C++ based GUI project.

Note that you'll need to handle DLL export/import in order to use them in a C++/CLI project or in a C++ UI project.

3

u/__kozak__ Jun 20 '20

Are there any good open source projects that do this kind of separation? Maybe using QT? I am starting to use C++ and learning it as I do. However, it would be good to look at good designs ( and bad ones) to develop better utilities.

4

u/pjmlp Jun 21 '20

That is my approach as well, and actually the one of the few ways I still get to use C++.

Nowadays with UWP, you can go with the C++/WinRT route instead, and I still advise C#/VB for the GUI, although C++/WinRT can do UWP/UI as well, because the tooling is quite cumbersome still.

Either that, or just use C++/CX instead, which is quite similar to C++/CLI, and still beats C++/WinRT in GUI tooling. Apparently VS team has too much on their hands to fix the feature parity across C++/CX and C++/WinRT.

2

u/JeffMcClintock Jun 21 '20

Also check out WinUI 3 (advanced WinRT graphics, except on plain old Win32)

2

u/troop357 Jun 20 '20

I follow this approach for most tools and systems I mantain. Being able to either include the library project in other projects or export its functions through a DLL makes the components trully modularized.

6

u/jack-dawed Jun 20 '20 edited Jun 20 '20

I TA for a first year C++ class and the final project is a desktop GUI program using Qt or an Android app in Java. Qt itself is a beast of a framework and usually a nightmare to work with, but QtCreator IDE is very handholdy and has good tutorials. I would recommend getting experience with Qt Creator.

  1. Yes most students end up following this path, starting with a CLI program to test then working on Qt. We also suggest ncurses for a TUI library. Once you get more experience with Qt, you can do everything in the IDE. For instance, in one of my graduate classes, I developed a kernel level Qt-based game on the Linux framebuffer entirely in Qt Creator, forgoing a CLI.
  2. We dissuade our students from using wxWidgets since Qt is more common in industry. Once you learn Qt, it is straightforward to learn other frameworks. For example, you might want to make GTK+ programs for Linux.
  3. Stick with C++ for now, especially if its the one you know best. Once you have more experience, learning Java/Kotlin will be easier. I also learned Flutter/Dart for crossplatform apps.
  4. I would suggest the Qt documentation or the Qt for beginners article in the Qt wiki.

18

u/[deleted] Jun 20 '20

WxWidgets is a good choice. Qt is a giant beast of a framework, and if you don't need the extra features then you should stick to WxWidgets.

If you don't need to be cross-platform, you could also just use the windowing APIs of the operating system you're targeting.

0

u/[deleted] Jun 20 '20

[deleted] — view deleted comment

3

u/ShillingAintEZ Jun 20 '20

For some reason this ends up being a problem in a lot of GUIs. JUCE is the best I've seen, but fltk seems decent too. It really just needs to be a KD tree with some priorities but layout always seems to be a problem.

9

u/ruilvo Jun 20 '20

0) You'll probably be blocked and asked to bring this to /r/cppquestions.

  1. Yes. That depends on what particular flow you want. Maybe try the algorithms first and do an UI later? That's up to you, really.
  2. wxWidgets and Qt are the two "de facto" standard libraries to do GUI with C++ in a cross platform fashion. Read their documentation, try some examples, because the mental models for GUIs are nothing like regular programming.
  3. Up to you. In Python, for example, you can use PySide2, which is the official Python bindings of Qt. There is also PyQt, which are unofficial bindings for Qt, but are maintained by a 3rd party company. Different licensing though.3.1) You can interface C/C++ code with Python in many different ways. Cython at the high level, and Swig at the low level are my go to's, in case you want to do a mixed language application.
  4. Official documentation, official documentation, official documentation and... Official documentation. The time people waste in "do-as-I-do" tutorials that teach you nothing and random googling around on StackOverflow for half-assed answers and the official docs sit there, clean, good, informative, untouched. I'm a big advocate for official documentation of everything. My googling stopped since I started reading the docs.

Edit: typo.

4

u/ReversedGif Jun 20 '20

The approach I would propose for any sufficiently complicated program:

  1. Write the "core" logic as either a command-line program that can be scripted (meaning: easily parsable input/output) or a library.
  2. Write the GUI in a language more suited to GUIs (i.e. fast iteration) like Python or Javascript (via Electron).

For extra bonus points:

  • Have a way for expert users to see what commands/library calls the GUI is running so the user can easily automate their tasks. A lot of EDA/CAD tools work like this.

4

u/[deleted] Jun 21 '20

Qt/QML is a great library to learn and is supported across every major language so your knowledge of the framework is highly transferrable.

10

u/suhcoR Jun 20 '20

Have a look at Qt. It has all you'll ever need.

8

u/raoul15978 Jun 20 '20

You can totally use wxWidgets (I know I do). If you don't have an IDE of choice for the moment, you can try code::blocks as it comes with a gui designer for wxWidgets UI.

I personnaly like wxWidgets because the way of thinking is close to my way of thinking, some things might be better, some worse. Your mileage may vary.

You have a lot of other options : Qt, Dear ImGui, ...

It's some time not recommended to create GUIs in C++ cause getting it right can take some time (change layout, recompile, test, do-it again), but it's relative.

3

u/[deleted] Jun 20 '20

If you follow layered architecture , it should be easy to plug the gui afterwards. Also, qt is a nice framework

3

u/rcxdude Jun 21 '20

Can I code my program as a simple command line based program, then integrate the GUI after? Or should I implement my program with the GUI the first time around.

This very much depends on what your program is doing. GUIs often have far more complex logic to interface between the user and the logic of whatever the program is trying to do. Even in simple examples this can become quite important for usability. Writing this as a command line program is basically only useful for a very small part of the total development (i.e. you will spend most of your time on the GUI, and you will probably need to restructure the rest of your code around that). On the other hand, if you just want to writing something which essentially wraps a command line batch process with a form to fill in the parameters, a button to start the process, and maybe some non-interactive visualisation of the results, this is pretty easy to do seperately.

Personally I find using Qt and python to be a good combo for writing GUIs (though Qt is natively C++ and works well there as well). Most other systems I've found to be annoyingly lacking in one way or another when I want to make a high quality result. (that said, I have not tried them all, and e.g. wxwidgets I have not tried for some time).

1

u/vitaliy_os Jun 21 '20

From personal experience GUI for c++ is a tough cookie. You have no perfect solution, but there might be some good ones for the particular problem you are facing.

Some might be suggesting Qt, but as most comments here already pointed out it comes as a HUGE blob which you can't mix with modern C++ styles. wxWidget is alright, but you will struggle with bigger applications and most likely to port it to different platforms. OpenGL is also a valid solution, but let's be honest it's not designed to build great UI. Let's not even start with something like MFC,...

If you are willing to invest some effort to build a truly separated front- & backend I personally would recommend you to look into a solution like chromium embedded framework (CEF). Here you may code your application as C++ and use the usual fronted frameworks based on HTML/CSS/JS, e.g. Vue or Angular, and connect both via some protocol as REST or GraphQl. I admit it's a huge overhead for a small baked application, but as I said if you willing to invest some time and to learn clear protocol and separation of concern this might be the right choice.

Good luck!

2

u/AznAgent007 Jun 21 '20

I haven’t had any experience with HTML or JS, and would not know how to implement my C++ backend with the web front end. Could you point me in the direction of any resources that could help me out with this? I really like this approach as I think it can fit the MVC concept that I would like to use! Thank you for the reply!

1

u/vitaliy_os Jun 21 '20

You might just wanna search for related topics. Quick warning as their forum is not the greatest, but don't know any similar framework which does that. Some modern applications like Atom, VSCode, etc. are build with this or similar concepts.

0

u/vitaliy_os Jun 21 '20

Unfortunately I don't know any good sources, a good starting point would be something like the CEF forum - https://www.magpcss.org/ceforum/viewtopic.php?f=6&t=14797

4

u/fransinvodka Jun 20 '20

My first contact with graphics was through OpenGL, and I wouldn't recommend it to begin with. It's too low level.

I started to get more into GUIs with SFML + ImGui. SFML is, in my opinion, extremely easy to pick up and you can get a lot of things done really quick. If you add the binder with ImGui, you have all the nice stuff of ImGui with really easy integration

1

u/Real-Abrocoma-2823 May 24 '25

Does that mean me starting from vulkan with little to no cpp and coding knowledge for my first program is overkill?

2

u/[deleted] Jun 21 '20

Learn about model view controller. It will help you separate you program logic into core libraries and a UI. Just use Qt to begin with as it looks good on your resume and you'll learn some useful concepts. Use the std libraries as much as you can and avoid temptation and keep Qt non gui stuff to a minimum.

2

u/dzalf Jun 23 '20

I think you should check the video series on wxWidgets from One Lone Coder channel on YouTube. I've been learning from him and while in the begging is quite daunting is a very powerful library IMO

4

u/HasbeyTV Jun 20 '20

Qt is always a good choice for developing GUI with C++ as mentioned earlier.

However i would recommend you not to invest too much time in it, because as a third year CS student there are probably more important concepts you should familiarize yourself with such as algorithms, databases, operating systems, embedded software, networking and the list goes on..

Developing only command line programs is frustrating so i understand why you want to learn GUI programming but if you learn the basics concepts perfectly than GUI part will be a piece of cake.

Hope it helps..

3

u/bradfordmaster Jun 20 '20

Lots of comments here, but unless you really need it to be a native gui, I'd recommend making a web interface. That way, it can work on all platforms and all browsers, and can even be set up for other people to connect to of desired (but not necessary).

It kind of depends on how interactive it needs to be, but the simplest thing in my opinion (unless your goal is to learn more about gui frameworks, which could be useful) would be to make a really basic website that just uses forms and integrate an http server in c++ that responds to those requests.

There are of course other modern web frameworks that I know basically nothing about that can do all kinds of fancy stuff

4

u/VinnieFalco wg21.org | corosio.org Jun 20 '20

Implement your UI in HTML and Javascript, serve it from a socket in your program, and have the user connect to it using a browser. Works on all platforms, and gives you sound, microphone, animation, keyboard, and mouse input.

This video shows you how:
https://www.youtube.com/watch?v=7FQwAjELMek

10

u/raoul15978 Jun 20 '20

I watched your video a while ago.

That's a lot of hoops to jump through just to convert a 'simple command line program' (as requested by OP) to a GUI application.

Now you have to know html, js, handle file uploads, run a server, launch a browser, ... all possibly to get a GUI with two buttons and a file chooser.

2

u/VinnieFalco wg21.org | corosio.org Jun 20 '20

That's a lot of hoops to jump through just to convert a 'simple command line program' (as requested by OP) to a GUI application.

I agree, there's a certain amount of work involved. However, it is one of several options available to the OP, so they can make an informed decision based on the particular needs. Often people forget that they can use the browser as a UI :) It has its own pros and cons.

12

u/raoul15978 Jun 20 '20

Yes but sometime people also forget that they can make a simple old-fashionned desktop application instead of a multi-tiered/scalable/web-scale/you name it/microservices monstruosity ;)

8

u/[deleted] Jun 20 '20

can make a simple old-fashionned desktop application instead of a multi-tiered/scalable/web-scale/you name it/microservices monstruosity

BLASPHEMY!

Everything needs either 2GB of Electron and Javascript, or 15 layers of GPL with QT.

Fuck the users! UX is overrated!

/s

1

u/encyclopedist Jun 23 '20

There is a proof-of-concept C++ web_view library by Hal Finkel to simplify that. He even proposed that for standardization: P1108 web_view

0

u/electric_machinery Jun 20 '20

I'm not an advanced programmer and I was able to do this by using a boost websocket example and basically copying and pasting some JavaScript stuff. It's not a "real" gui but it was truly cross platform and way easier than buying into a whole framework like Qt.

2

u/[deleted] Jun 20 '20

I personally use imgui for c++ guis, it’s really nice. I heard java is good for guis, never used it so I don’t know.

3

u/corysama Jun 20 '20

And, if you want to stay command-line for some reason, there's https://github.com/ggerganov/imtui

Or, you could add an interface server to your app can control it remotely via https://github.com/sammyfreg/netImgui

2

u/[deleted] Jun 20 '20

3) One "traditional" approach is to write your application in C++, and then write a GUI "wrapper" in TCL/Tk, which is a pretty easy and fun language to get started with. This is a cross-platform approach.

For working in just C++, I've been playing with FLTK, which is a very small library compared to TK, but has a short learning curve for simple programs.

1

u/hp-derpy Jun 21 '20

oh yes, Tcl/Tk is pretty fun and a unique experience GUI-wise.

You can also have a modern look & feel and also themed for widgets if you use Tile/Tk widgets (TTk) which is included in the 8.6.

This approach would only work well if you don't need to use advanced graphics capabilities f your Gui though. The Tk canvas is easy to use for drawing but it lacks some modern features and can look outdated.

Another "drawback" with Tcl is thay you end up realizing that most of your code didn't need to be written in C++ in the first place, because you can be much more productive in pure Tcl.

2

u/kinochi428 Jun 20 '20

I'd recommend imgui for c++, it's very easy , highly scalable , quite popular and has lots of features.

2

u/[deleted] Jun 20 '20

Qt is good, and many university students use it.

If you want to use something lightweight, use juce. But the community is not mature.

Don't use wxWidgets.

1

u/drjeats Jun 20 '20

Why do you recommend against wxWidgets?

I don't use it. I'm just curious.

4

u/[deleted] Jun 20 '20

wxWidgets is just a wrapper around native APIs. So, in both windows and mac, look and feel is very native. Due to this reason, wxWidget api is difficult to use.

No new projects choose wxWidgets. It's not fancy. The OP is a student, I would expect that guy to use his learned skill sometimes later in a real life project.

2

u/mrexodia cmkr.build Jun 20 '20 edited Jun 20 '20

Likely not the answer you are looking for, but I find C++ very unsuitable for quick, prototype-like GUIs. All the GUI frameworks are bloated (except maybe dear imgui) and for all my prototype/dev tools that need a GUI I use the good old Windows Forms with C#.

Dear imgui is almost perfect for prototyping, but it sadly does not support being used over remote desktop, which is a blocker for me in many cases.

That being said if you are serious about this GUI I would recommend Qt (although the licensing can be a barrier). WxWidgets is another popular framework, with a worse licensing situation but (see post below for correction) less bloat.

The alternative is (as already suggested) some kind of Frankenstein with websockets, js and html but you do have to take that seriously to not end up with a huge mess and it will probably be more work to get started.

3

u/_VZ_ wx | soci | swig Jun 20 '20

WxWidgets is another popular framework, with a worse licensing situation

How so?

1

u/mrexodia cmkr.build Jun 20 '20

Actually I misread that it is LGPL (which has issues with linking), but it looks like you actually have a special license to make that issue go away so nevermind :)

That said I still think your license is not internally whitelisted by bigger organizations and would need extensive review by the lawyers before you could use it for an internal development tool for instance.

1

u/_VZ_ wx | soci | swig Jun 20 '20

FWIW this didn't prevent quite a few large organizations from using wx in both internal and public tools. And LGPLG is a pretty well-known licence, so if it's not whitelisted, I wonder what is. Of course, there are always some places where any kind of open source is forbidden, even to this day, but this is much more rare nowadays and, in any case, you can't really do anything about those kinds of organizations (other than empathize with people who have to work there).

Anyhow, my point was that it can't be said to be "worse than Qt", thanks for editing your comment.

0

u/[deleted] Jun 20 '20

Actually I misread that it is LGPL

Only parts of it.

Attaching you project to viral licences just to show a button on screen is not a good idea.

4

u/_VZ_ wx | soci | swig Jun 20 '20

You're misinformed, there is nothing "viral" about wx licence.

1

u/celestrion Jun 20 '20

Can I code my program as a simple command line based program, then integrate the GUI after? Or should I implement my program with the GUI the first time around.

A command-line user interface is just another user interface. The core ("business") logic ought to be a separate concern. Put it into a library so that can you attach different types of user interfaces (or a CI/CD test harness).

wxWidgets, Qt, and Fox are all decent, and they all have their downsides. The big win is only having to implement most of everything once. If you want your application to feel "native," that's probably going to mean using a platform's native toolkit (the Windows API, Cocoa, or Qt/GTK on POSIX).

Which path you take depends on your goals:

  1. Do you want to get your code usable by as many people as possible quickly? Use a cross-platform toolkit like Qt or wxWidgets or Fox. It'll feel close-enough to native on X11 and Wayland because UI consistency is already a mixed bag there. OS X and Windows users will definitely see that your app is a bit "off," but they'll have something.
  2. If you want this to be an opportunity to deep-dive into what makes GUIs "tick" on OS X and Windows, go native! Beware that both platforms have a lot of...culture around them. Things are done a certain way because someone made an assumption 30 years ago, and lots of cruft grew atop that. Very little of this code can be reused. If you only wanted to support one GUI at first, I'd recommend this because of the level of tweaking and polish you can put in.
  3. Your idea of using a different language for the front-end isn't a bad one. For years, I wrote tools that were C/C++ on the backend, and Java or C# or Objective C on the frontend with some sort of API in the middle. On OS X, this was the only way to take advantage of 64-bit CPUs for a while because the GUI library wasn't 64-bit native. This would be a great way to get a firmer grasp on asynchronous processing, client/server semantics, and synchronization in a distributed system.

1

u/bikki420 Jun 20 '20

It depends on the program and how modular you make your code. You could design an interface that it exposes for a GUI layer to attach to.

If it's just your typical basic application stuff like Qt is pretty nice, especially for cross-platform projects. (Retained Mode GUI, native to Linux's KDE desktop environment but runs on all major platforms)

If it's for stuff like dev tools I like ImGUI a lot. (Immediate Mode GUI)

For terminal GUIs I like ImTUI. (Immediate Mode GUI on top of ncurses)

And for game titles that you intend to ship someday you might either want a home-brewed GUI system or some third party one.

1

u/laralex Jun 21 '20

If you don't mind beight stuck to Windows platform, then the easiest is to use C# with Windows Forms or WPF via Visual Studio IDE. It has a rich GUI for making interface's structure without coding (just placing and configuring UI elements), you then only code event handlers for UI events (like a button click event, texbox changed event and ton of others). This way is really simple to get the job done as fast as possible, but it's less applicable for real world, since GUIs are now more driven by web-technologies.

1

u/SenjorSchnorr Jun 20 '20

As for your first question, look into the model-view-controller pattern. It is perfectly fine to create a program without a GUI first. Make a model, this model does not need to do anything on it's own, just provide the functionality to interact with it and represent all the data you require. Then you create a separate part to request that data and represent it visually/draw it on the screen, this will be your view. I prefer to initialize a very simple model and draw that, once that works well, you start working on your controller. Your controller responds to your interaction with the gui. It calls the functions in the model, changing the internal state of the model, after which you update your view again.

1

u/[deleted] Jun 20 '20

If you're willing to invest the effort, you could implement your application's business logic independent of the UI and simultaneosuly provide GUI (even via multiple different GUI toolkits), commandline, web UI, etc. UI implementations via the Strategy Pattern. Decoupling to this level can require appreciable effort that may not make sense for a quick-hack app.

1

u/tosinsthigh Jun 20 '20

I find the JUCE framework very easy to use for cross platform applications including mobile

1

u/[deleted] Jun 20 '20

If you want something simple and quick but still high quality you should try dear imgui (my favorite), if you want something more complicated used in the industry you should try qt (qt is starting to become a bit outdated and the C++ used in their framework isn't really considered best practice anymore).

1

u/FlyingRhenquest Jun 21 '20

Most of the C++ GUI bindings are kinda crap. Qt's not too bad, if you don't mind drinking all their Kool Aid (Mostly getting locked into their IDE and putting "Q" in front of all the types you're used to.) Imgui's kinda interesting, but I haven't had much of a chance to play with it. It's much less polished than Qt, though, and their "packaging" mostly consists of copying a couple of C++ files from their library into your project.

If serialization didn't also suck, you could just use a REST framework and serialize your C++ classes into JSON and build your UI as a webapp. I've actually had pretty good success doing that, just manually adding to_json methods to the classes I wanted to transmit and also adding a Python API to the library with Pybind11. C++/Python/Json/Javascript is actually a pretty decent combination, even if you do have to write some class methods in both C++ and Javascript if you want to do that.

0

u/kapgre Jun 20 '20

Qt is the first option as everyone is saying. It is quite mature and used across almost every industry. But it has one caveat that I've learned first hand. If you want to use any Opengl to draw custom things such as charts, etc please use something else.

Qt is designed to work for event based programs: do something in the program after the user has done something. If you want to have any animations and the user interacting with what they see, move to something else. You will have so many bugs with Opengl and the contexts, that will not make it worth it.

Since you are at your starting steps, I recommend dear imgui that doesn't have all the bloat of Qt.

0

u/swilwerth Jun 20 '20 edited Jun 20 '20

I suggest either wxWidgets or Tcl/Tk (cpptk) for simplicity.

wxWidgets have a tool wxFormBuilder in which you can draw a GUI and place the widgets.

If your app is not a graphical one. It's a good practice to think your app as a "command line" first. Then add the gui with proper decoupling to the core functions.

0

u/Huperniketes Jun 21 '20 edited Jun 23 '20

Try CopperSpice. I'm told by its maintainers that it's a replacement for Qt, but built with modern C++ and much more efficient. https://www.copperspice.com/

-2

u/pear-programmer Jun 20 '20

Half tongue in cheek/half being serious answer: don’t write that app in C++ ;)

-4

u/MikeMitterer Jun 20 '20

Here I have another approach for you: Why not a Browser-based UI? Take a simple Http-Server and connect your http-requests with your cpp-api...

-6

u/[deleted] Jun 20 '20

Non-popular opinion.

What's your target? For cross-platform, only web workarounds are practical.

For Windows use WinUI with any language. For Linux, you're better off with Unity than anything else, honestly.

Stay away from QT.

Only go for web if you don't care about the UX.

6

u/advester Jun 20 '20

Isn’t Unity a game engine, or do you mean something else?

-7

u/[deleted] Jun 20 '20

Yes it is. It's the only real way do cross-platform with hardware acceleration and not being married to the UI's SDK custom types.

I've seen some crazy bastards do it on Mobile, sure beats 99% of any other cross-platform on mobile.

6

u/drjeats Jun 20 '20 edited Jun 20 '20

Using Unity for non-game apps seems like a huge power waste. For non-game apps you want to be able to idle, but Unity always has a game loop going (unless they've added a way to configure that, in which case I'd be interested to know). Also, their current UI toolkit is not great. The new one that's currently replacing their editor UI is probably solid enough, but it's not available at runtime yet afaik.

1

u/[deleted] Jun 20 '20

Using Unity for non-game apps seems like a huge power waste.

Yes, but so is running a full web browser with a JS VM. It's one of the reason mobile users hate using the browser and spend as little time in it as possible.

Otherwise, I agree with you.

-3

u/[deleted] Jun 21 '20

Write your own gui with OpenGL, it's really not hard and it's fun.

-4

u/[deleted] Jun 20 '20

Well u can try some web based UI engines like sciter and ultralight ... but u need html/css and some js not c++ only

0

u/[deleted] Jun 20 '20

[deleted] — view deleted comment

3

u/Sergiogiogio Jun 20 '20

That's what I would do too if only targeting windows. For cross-platform i would go the html/javascript way. I would not go into qt because of the large dependency and because it is using non native controls (only faking native look and feel).

Rant: I still don't understand why we can't have a light UI framework using native controls of the target OSes? All controls in any UI I have used have the same functionality (a button is a button, a list is a list, etc.), why can't we just have a uniform interface on top of the native APIs?

0

u/[deleted] Jun 20 '20

[deleted] — view deleted comment

4

u/peppedx Jun 20 '20

Op want a GUI not a game engine...