GUI Composition in Qt - c++

I have experience building GUIs in Java, C#, and C++ using the WinAPI. I'm attempting my first GUI in C++ using Qt and I have a bit of a transition problem. In any of the other three GUI paradigms, I could create my own GUI components, extend existing JPanels, etc. and end up with a custom-made GUI element that I could add to other GUI windows. C# is particularly good at this as anything I create automatically shows up in the Toolbox after it compiles.
From what I can see there are only two options in Qt and I'm hoping there is something I'm missing. The options are:
Create a custom Widget which may then be imported using a widget container promoted to the right widget.
Build what I like and drag it to scratchpad, from where I can replicate it to my heart's content.
The problem is that I want dynamically add/remove GUI elements at run time. For example, I have a Model-View-Control pattern. The view and control are two different panels in the GUI. When I switch to a different view in one panel, I want to remove the control from the other panel and replace it with the right control for the new view.
From what I can tell, I could do this using custom widgets, but it seems extremely heavy handed to do this for tons of minor widgets in composition to a greater capability. And although I can do the kind of composition I want in scratchpad, I can't figure out how to dynamically add something I have saved in scratchpad.
It is also possible that there is a Qt way of doing things which I have not found. For instance, I have some friends that have successfully created the effects above using different tabs. That seems like a cheap answer, which I could use, but I'd like to believe that Qt has sufficient flexibility to let me build any kind of GUI.
Any suggestions would be helpful
---------------------Improved example--------------------
Let me use the example code that #m7913d gave. (http://doc.qt.io/qt-5/qtwidgets-layouts-basiclayouts-example.html) Suppose that I want to make this portion of the gui into a reusable component which i can add to any GUI I want. How do I do that?
If this was C# I would create a new user control, add the GUI elements, set up the code that makes the unit work as a whole and possibly set up event listeners or properties of the user control as a whole. then I can instantiate, add, and remove them at will from the rest of the GUI. That is what I want.

Related

QT many layers of window

Recently I've been working on my project in QT creator. I wanted to build it only on one window but I find it difficult. I've not found something like layers, that I can apply to the window.
What i mean is that I'd like to hide actual content of my window and replace it with other. How could I make many layers in Designer mode?
You might want to look at QStackedWidget:
The QStackedWidget class provides a stack of widgets where only one widget is visible at a time.
But don’t overdo it. After a certain point complexity tends to kill you quickly in Qt Designer. One simple solution is to design each of the “layers” in their own QWidget-derived class and just combine them on the final QStackedWidget. That last step is probably simple enough that you don’t even need Designer for it.

Container for precompiled GUI Blocks

so here's my problem. I have a (large and growing) set of single-window applications written in C++ with a QT GUI. Basically each of these programs is used to connect with a different hardware device and consists of a couple of input parameters and a "Connect Button" and is around 300x400px in size.
Note: I can access, modify and compile these applications.
What I want now is another (QT) application that allows me combine multiple of those applications above into a single window. I'm thinking like an "Add new Device"-button where I can select one of the existing applications and then it's added to the 'container'.
I don't want to have duplicate code, so I don't want to copy the code from all the applications and include it to one large application. All the application logic should remain within those little programs. Then I want to compile them and only provide those compiled files to the Container-Applications.
Is there a design pattern for something like that? Is there a way to have a common base ui-class (implementing QWindow or something like that) to achieve this behavior with QT?
Thanks in advance. Kind regards

Creating a wxWidgets GUI with multiple stages

There's lots of information about creating different layouts, dialogues, even custom controls. However I've not been able to find out how to create a window that has multiple seperate "stages", like an installer, or many of Visual Studio's project wizards.
I guess it could be done by keeping the information seperate from the controls and updating the information on stage changes as needed, then deleteing everything and recreating the window contents each time, but is this really the only and best way? Are there issues with the window size, layout, etc. that I will need to deal with that don't occur when everything is added in the frames constructor?
wxWizard is a great class, but I would suggest it only when you have linear flow of steps/stages.
I think the best idea for you is to create non-re-sizable (just do not use wxRESIZE_BORDER style) frame and set of classes that create/destroy in-line layout on demand. Another option is to extend wxWizard class and supply more navigation functionality to it, but I have doubt you really need that.

Creating a professional-looking (and behaving!) form designer

When I began programming (some 10+ years ago), three things amazed me:
Compilers/interpreters (back then I knew them as "programs that make my programs work", often followed by the qualifier "whatever they are")
Code editors
Form designers
Back then, I accepted all of them as facts of life. I was able to make my own special-purpose programs, but "programs that made my programs work", code editors and form editors were made by the Gods and there was no way I could mess with them.
Then I went to university, and took a course on formal language processing. After learning formal grammars, parsers, abstract syntax trees, etc.; all the magic about compilers, interpreters and code editors was soon gone. Compilers and interpreters could be written in sane and simple ways, and the only non-sane thing a syntax highlighting code editor could require were Windows API hacks.
However, to this day, form editors remain a mystery to me. Either I lack the technical knowledge required to make a form designer, or I have such knowledge, but cannot find a way to use it to implement a form designer.
Using Visual C++ and the MFC, I would like to implement a form designer inspired by the best form designer ever:
In particular, I would like to imitate its two features that I like the most:
The form being designed is inside a container. Thus, an arbitrarily large form may be designed without wasting too much screen real estate, by simply resizing the container to an appropriate size.
The "Align to Grid" option makes designing professional-looking user interfaces a lot less
frustrating. In fact, I would go as far as saying creating professional-looking user interfaces using Visual Basic's form designer is actually easy, fun and enjoyable. Even for left-brained programmers like me.
So, I have the following questions:
How do I make a form designer, in which the form being designed is inside a container? Is the form being designed an actual window contained inside another window? Or is it just a mockup "manually" painted by the form designer?
Do the Windows API and/or the MFC contain functions, classes, whatever that make it easy to create "selectable" items (surrounded by little white or blue boxes when they are selected, resizable when they are "grabbed" by one of these "edges")?
How do I implement the "Align to Grid" functionality?
Both the answers here are good, but left out what I consider to be the really interesting bits (including a couple that you didn't ask directly, but you might find of interest anyhow), so here's my 2c:
Drawing the controls
Ideally, you just go ahead and create a regular instance of the control. You want something that looks like a button? Create a real button. The tricky thing is stopping it from behaving like a button: you want clicks to activate it for moving, not actually 'click' it.
One way of dealing with this - assuming that the controls in question are 'HWND-based' (eg. the standard windows set of button, edit, static, listbox, treeview, etc.) - is to create the control, and then subclass it - ie. override the wndproc with SetWindowLongPtr(GWLP_WNDPROC, ...), so that the designer code can intercept mouse and keyboard input and use it to initiate a move, for example, instead of having the mouse input go through to the actual button code, which would instead interpret it as a 'click' event.
An alternative approach to subclassing is to place an invisible window above the button to capture the input. Same idea of intercepting input, just different implementation.
The above applies to both managed (VB.Net, C#) and unmanaged (C/C++) controls; they're both essentially stock windows HWNDs; the managed versions just have a managed wrapper code handing off to the underlying unmanaged control.
The old (pre-managed code) ActiveX controls, as used in pre-.Net VB, were a whole different ball game. There's a fairly complex relationship between an ActiveX container and the ActiveX controls within it, with many COM interfaces handling things like negotiation of properties, events, painting, and so on. (There's event a set of interfaces that allows an ActiveX control to receive input and draw itself without having its own HWND.) One benefit you get from this complexity, however, is that ActiveX controls have an explicit 'design mode'; so a control knows to respond appropriately in that case and can cooperate with the whole procedure.
The Form Itself...
So basically the controls are just regular controls. So you'd expect the form itself to be a regular form? - Almost. As far as I know, its just another HWND-based window, that's a child of the designer (so it gets clipped, and can be scrolled within it); but I think the designer is doing a bit of 'cheating' here, because usually Windows only draws frames like - with titlebar and min/max buttons that for actual top-level windows. I don't know offhand the exact technique that they're using here, but some options could include: painting it manually to mimic the Windows look; using the Windows "theme" APIs, which allow you to access the graphic elements used for the bits and pieces of titlebars and paint them wherever you want to; or, perhaps less likely, setting the window up as a "MDI Child window" - this is one exception case where windows will draw a frame around a nested window.
Draggable Handles
Simplest approach here is for the designer to create eight small square title-bar-less popup windows that sit above all the other elements - which initiate the appropriate resize code when they are clicked. As the user clicks from control to control, just move the drag handle windows to the currently active control. (Note that in all the above, Windows itself is figuring out who's been clicked, you never have to actually compare mouse coords against element rectangle coordinates and work it out yourself.)
Saving & Recreating
For plain windows system controls that are used by unmanaged C/C++, it's relatively easy: there's a well-known text-based file format - .rc - that describes the controls and locations. Have the designer spit out that (and likely a resource.h file also) and you're done: any C/C++ project can pick up those files and compile them in. Managed code (C#, VB.Net) has a somewhat more complex scheme, but it's still the same basic idea: write out a description in the style that the managed tools expect, and they'll happily compile it and use it.
(ActiveX controls are - you've guessed it - a whole 'nother story. There isn't a standard format that I'm aware of, so the form editor and runtime that consumes the data would be closely tied together - eg. the form editor from pre-.Net VB6 produces forms that only VB can use. - I think. It's been some time ago...)
As for recreating the form: if you have a .rc file, it gets compiled into a dialog resource, Windows has built in support to recreate those. Likewise, the managed code support libraries know how to recreate a form from its particular format. Both basically parse the description, and for each item, create elements of the appropriate classes, and set the appropriate style, text, and other properties as specified. It's not doing anything you can't do yourself, its just helper utility code.
Handling Focus
For a collection of HWNDs in any container, whether in 'test' mode or actually running in the real app, and regardless of whether you let Windows or Winforms handle the form creation or whether you created each HWNDs yourself, you can add tabbing support by calling IsDialogMessage in your message loop: see the MSDN page remarks section for details. (While WinForms could do this, I think it actually does its own focus handling, so that it can have tab order independent from visual stacking Z-Order.)
Other Things To Explore...
Make friends with the Spy++ app (part of the SDK, installs with Visual Studio). If you're going to do anything with HWNDs, managed or unmanaged, it's a real good idea to know how to use this tool: you can point it at any piece of UI on Windows, and see how it's constructed out of a tree of different types of HWNDs. Point it at the VB designer and see what's really happening for yourself. (Click the 'binoculars' icon on the toolbar, then drag the crosshairs the the window you're interested in.)
Also take a look at the resource files that the designer spits out. Everything that you can tweak or move or edit in the forms designer corresponds to some item somewhere in one of those resource files. Make a copy of them, tweak some settings, and then file-compare the two sets, and see what's changed. Try changing some things in the files by hand (I think they're nearly all text), reload, and see if the designer picked up your changes.
Other Things To Note...
Much of the above is specific to Windows - notably the fact that since we're using Window's own building blocks - HWNDs - we can get Windows itself to do some of the hard work for us: it gives us the facilities to reuse the controls themselves at design time so we don't have to draw mock-ups; to intercept input on other controls so we can make a click into a move or whatever other action we want, or figure out which control is clicked without having to do the location math ourselves. If this was a designer for some other UI framework - say Flash - which doesn't use HWNDs internally, it would likely instead use that framework's own internal facilities to do similar work.
Also, it's far easier if you limit the number of controls in the palette to a small finite set, at least at first. If you want to allow any control at all to be dragged in - eg. a 3rd party one, or one you've used in another project; you typically first need some way for that control to be 'registered' so that the designer knows that it's available in the first place. And you may also need some way to discover what icon it uses in the toolbar, what its name is, what properties it supports - and so on.
Have fun exploring!
You implement a form designer almost like a normal GUI. You have stuff you can drag (your widgets), you have stuff you can click (your buttons) and you have stuff you can select (your placed widgets) and that's really about it.
Q: Now, how do you display a window in a GUI?
A: You paint it, simple as that.
Q: And how do you keep stuff inside that window?
A: You check against the bounds of the "parent" object. You could almost say that a form designer is like a little game and you have a scene graph holding all your widgets, connected by parent-child-relations.
Q: Then, how do you select stuff in a GUI?
A: Check the current mouse position on-click against the bounds of all (near) widgets (a scene graph only helps here, like a quadtree).
Q: How do you align widgets on a grid?
A: For the grid alignment, let's have a simple example: Say your real resolution is 100px on the x-axis, but you want your grid to only have a resolution of 10px on x. Now say you move your widget by 28px in real resolution. To get the grid resolution, you simply divide by 10, get 2.8, round that, and finally move the widget 3 tiles on x. The rounding is the key here. only if the grid movement is >= ?.5, you snap to the next tile. Otherwise you simple stay at the old one.
Hope this can give you a general hint on how to start a form designer. Have fun. :)
(PS: Don't know about any specific WinAPI/MFC functions/class to help you along, sorry.)
Just to add a point or two to what #Xeo has already said:
First of all, no, you don't always draw all the content yourself. During normal design phase you're basically just drawing something that looks like the control, but (at least IIRC) it also lets you "run" a form in test mode (certainly the VC++ dialog designer does, and even though VB's was more primitive, I think it did have that particular capability as well). Test mode was when you can "run" a form before you've (necessarily) attached any code to it -- even though clicking a button (for example) doesn't do anything in the surrounding program, the control itself works as normal -- a button clicks normally, an edit control will let you edit, etc.
That is done by actually instantiating a control, telling it the correct position, size, and properties. ActiveX controls do quite a bit to support this, and the previous "Windows custom controls" did as well, though with considerably less sophistication. From the viewpoint of the control, it's working just about exactly like it normally would, receiving input, sending notification to its parent, etc. The only thing that's changed is that the parent most ignores most of the notifications it receives, but the control doesn't really know that.
There are two basic ways to do this. One is to create a collection of controls yourself, along with their positions, sizes, etc., and use CreateWindow (or CreateWindowEx, etc.) to create window of the correct class. While relatively easy to handle, this has the disadvantage that it leaves all the tab-handling to you.
The other possibility is to create a DLGTEMPLATE structure to hold data about the dialog box, and a some DLGITEMTEMPLATES for the individual controls, and finally use CreateDialogIndirect to create a dialog box with those specs, holding those controls. It's tedious, but it works, and when you're done it handles tabbing between controls automatically (and works the same as any other dialog, since it's the same Windows code creating it either way).
Second, since you've tagged this C++, you might want to take a look at some code on CodeProject that actually implements a dialog editor. Although it isn't quite as sophisticated as some of the commercial ones, this is a reasonably complete form/dialog editor, complete with most of what you've asked about.

Hand Coded GUI Versus Qt Designer GUI [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I'm spending these holidays learning to write Qt applications. I was reading about Qt Designer just a few hours ago, which made me wonder : what do people writing real world applications in Qt use to design their GUIs? In fact, how do people design GUIs in general?
I, for one, found that writing the code by hand was conceptually simpler than using Qt Designer, although for complex GUIs Designer might make sense. Large GUIs might be possible using Designer, but with time they might become very difficult to manage as complexity increases (this is just my opinion). I also downloaded the AmaroK source code to take a peek at what those guys were doing, and found many calls to addWidget() and friends, but none of those XML files created by Designer (aside: AmaroK has to be my favorite application ever on any platform).
What, then, is the "right" way to create a GUI? Designer or code? Let us, for this discussion, consider the following types of GUIs :
Simple dialogs that just need to take input, show some result and exit. Let's assume an application that takes a YouTube URL and downloads the video to the user's hard disk. The sort of applications a newbie is likely to start out with.
Intermediate level GUIs like, say, a sticky notes editor with a few toolbar/menu items. Let's take xPad for example (http://getxpad.com/). I'd say most applications falling in the category of "utilities".
Very complex GUIs, like AmaroK or OpenOffice. You know 'em when you see 'em because they make your eyes bleed.
Our experience with Designer started in Qt3.
Qt3
At that point, Designer was useful mainly to generate code that you would then compile into your application. We started using for that purpose but with all generated code, once you edit it, you can no longer go back and regenerate it without losing your edits. We ended up just taking the generated code and doing everything by hand henceforth.
Qt4
Qt4 has improved on Designer significantly. No longer does it only generate code, but you can dynamically load in your Designer files (in xml) and dynamically connect them to the running objects in your program -- no generated code however, you do have to name the items in Designer and stick with the names to not break your code.
My assessment is that it's nowhere near as useful as Interface Builder on Mac OS X, but at this point, I could see using the Designer files directly in a program.
We haven't moved back to Designer since Qt3, but still use it to prototype, and debug layouts.
For your problems:
You could probably get away with using the standard dialogs that Qt offers.
QInputDialog or if you subclass QDialog, make sure to use QButtonDialogBox
to make sure your buttons have the proper platform-layout.
You could probably do something more limited like xPad with limited Designer functionality.
I wouldn't think you could write something like OpenOffice solely with Designer but maybe that's not the point.
I'd use Designer as another tool, just like your text editor. Once you find the limitations, try a different tool for that new problem. I totally agree with Steve S that one advantage of Designer is that someone else who's not a programmer can do the layout.
In my experience with Qt Designer and other toolkits/UI-tools:
UI tools speed up the work.
UI tools make it easier to tweak the layout later.
UI tools make it easier/possible for non-programmers to work on the UI design.
Complexity can often be dealt with in a UI tool by breaking the design into multiple UI files. Include small logical groups of components in each file and treat each group as a single widget that is used to build the complete UI. Qt Designer's concept of promoted widgets can help with this.
I haven't found that the scale of the project makes any difference. Your experience may vary.
The files created with UI tools (I guess you could write them by hand if you really wanted to) can often be dynamically loaded at run-time (Qt and GTK+ both provide this feature). This means that you can make layout changes and test them without recompiling.
Ultimately, I think both raw code and UI tools can be effective. It probably depends a lot on the environment, the toolkit/UI-tool, and of course personal preference. I like UI tools because they get me up and running fast and allow easy changes later.
The organisation I work for has ported its GUI application to Qt several years ago.
I think there are several aspects that are worth mentioning:
Working with Qt Designer, at least at that point, was not a realistic option: there were too many features that couldn't be done with Qt Designer;
Conventions and structure that had to be preserved prevented the use of Qt Designer;
Once you've started without Designer, it is probably difficult to return to it;
the most important aspect, though, was that the programmers were very much used to programming using vi or emacs, rather than using a GUI IDE.
My own experience, which goes back approx. 4 years, using Qt3.3, is that dynamic behavior in dialogs was not possible to realise in Designer.
Just to say I've written and maintained complex GUIs in Qt without using Qt Designer -- not because I don't like Qt Designer, but because I never got around to working that way.
It's partly a matter of style and where you're coming from: when I started on Qt, I'd had horrible experiences of Dreamweaver and Frontpage and other visual HTML tools,and far preferred writing code with HomeSite and resorting to Photoshop for tricky layout problems.
There's a danger with visual code IDEs that you try to keep within the visual tools, but end up having to tweak code as well -- in ways that aren't well understood.
Learning iPhone development, for example, I've found it frustrating to hit 'magic' visual stuff ('drag from the empty circle in the Connections inspector to the object in the Interface Builder window...') that would be simpler (for me) to understand in plain old code.
Good luck with Qt -- it's a great toolkit, however you use it, and Qt Creator looks like being a great IDE.
I'd add that one of the reasons for using graphical designer was the lack of layout managers in Win32, for instance. Only absolute positioning was possible, and doing that by hand would have just sucked.
Since I switched from Delphi to Java for GUI apps (back in 2002), I've never used designers any more. I like layout managers much more. And yeah, you get boilerplate code, but moving objects on a UI designer may take as much time as changing the boilerplate. Plus, I would be stuck with a slow IDE; that's for the Java/C# case, OK, while for Qt (especially Qt4) it doesn't apply. For Qt3, I wonder why one should edit the generated code - wasn't it possible to add code in other files? For which reason?
About the discussed cases:
1) Hand Coded GUI is likely faster to write, at least if you know your libraries. If you're a newbie and you don't know them, you may save time and learn less with a designer, since you don't need to learn the APIs you use. But "learn less" is the key factor, so in both cases I'd say Hand Coded GUI.
2) Menu bars are quite annoying to write code for. Also, think to details like accelerators and so on. Still, it depends on what you're used to. After some time, it may be faster to type that boilerplate than to point-and-click into designer to fix all those properties, but just if you can really type like into a typewriter (like those admins for which typing Unix commands is faster than using any GUI).
3) I'd extend the answer for case #2 to this one. Note that, for Win32 platforms, it may be possible that using designers which generate Win32 resources might be faster to load (no idea about that).
However, I'd like to mention a potential problem with using Qt Designer there. Real world case: it took some seconds (say 10) to load a complex Java dialog (the Preferences dialog box for a programmer's text editor) with a lot of options. The correct fix would have been to load each of the tabs only when the programmer wanted to see them (I realized that after), by adding a separate method to each preference set to build its GUI.
If you design all the tabs and the tab switcher together with a designer, can you do that as easily? I guess there might be a similar example where a hand coded GUI gives you more flexibility, and in such a big app, you're likely to need that, even if just for optimization purposes.
One of the main benefits of using designer to create GUIs is that other programmers can change or maintain forms and widgets easily without the need to delve in to a complex code.
Its strange that you're saying the writing code is simpler than manipulating objects in a graphical environment. It's a no-brainer.
The designer is there to make your life easier and in the long term it makes your code more maintainable. It's easier looking in the designer to see what the your UI looks like then reading the code and trying to imagine what it might look like.
With current Qt you can do almost everything from within the designer and the very few things you can't do, you can fix with very few lines of code in the constructor.
Take for instance the simplest example - adding a signal-slot connection. Using the designer it's as simple as a double click. Without the designer you need to go lookup the correct signature of the signal, edit the .h file and then edit write your code in the .cpp file. The designer allows you to be above these details and focus on what really matters - the functionality of your application.
I like to first turn to the designer to develop GUI widgets. As mentioned in the other posts, its faster. You also get immediate feedback to see if it "looks right" and isn't confusing to the user. The designer is a major reason I choose Qt over other toolkits.
I mostly use the designer to make the one-off dialogs.
Having said that, I do the main window and any complex widgets by hand.
I think this is the way Trolltech intended. QFormLayout is a class they provide to easily programatically create an input dialog.
By the way, the designer in Qt 4 is not an IDE like the one they had in Qt 3. It's just an editor for editing .ui files. I like it that way. The new cross platform IDE is going to be called Qt Creator.
It's an old post but I would advise you to look at Clementine - a music player which (I think) derives from Amarok. They use Qt4 and from what I can see there is a ui folder in the src folder of the project. In the ui folder as one might expect they have all sorts of .ui files. If you compile and start Clementine you will see that the GUI is fairly complex and quite nice.
For me, it depends how much logic is encapsulated in the widget/GUI. If it's just about simple forms, I prefer to use QtDesigner.
If it contains complex checks or interaction, I tend to program it.
We're using the Qt Designer if anyone needs to create a Gui.
The thing is to create just little Widgets for certain tasks (like you would do in a class-design) and then get them together into a "parent-gui".
This way your widgets are highly reusable and could be used for Guis in a modular way. You just have to specify which signals each Widget is sending and which slots they provide.
We additionally are creating .ui-Files which than could be generated during build-process. Until now there was no need to edit those files by hand.
Build different parts of your UI
in different .ui files using QtDesigner,
then bring them together (and add complications) in code.
There are things you can't do in Qt Designer, you can only do in code,
so Qt Designer is just one (great) part of the tool chain.