Qt - Adding dynamic controls to a placeholder - c++

I am looking for the best way to dynamically swap in and out controls within Qt on a predefined layout created from the Qt Designer.
I come from a ASP.NET background, where often I would use the idea of a "placeholder" for this type of task and add controls as children at runtime.
Does Qt support this type of functionality or something similar?

You can just add a layout control to any widget and later on dynamically add controls to the layout:
for(int i = 0; i < 10; i++)
{
QLabel *plbl = new QLabel(myform);
plbl->setText(QLabel::tr(L"My dynamic text box"));
mylayout->addWidget(plbl);
}
Edit: There are different Layout classes that support different "fill" styles (e.g. horizontal next to each other, grid layout, vertical layout, etc.). You won't need any placeholders or similar - just a widget (or layout) as parent to fill.

If your Qt Layout already uses layouts, then best idea would be to leave some place for runtime controls in layout tree, or perhaps even a empty layout just for those. Layouts have ability to dynamicaly add or remove widgets and sub-layouts, so that solves the problem. If you want to insert new widgets immediatley after removing old ones interface might flicker as qt will try to reuse temporarly freed space. It might slow application down if there are any slow rendering widgets.
Another soultion would be to insert empty widget - that is more similar to ASP.NET approach. It is a bit more crude method, but might be a good way to avoid flickering of interface. It would prevent layout from reusing space even if you don't display any widget and leave unused space - it might suggest to a user, that after some interaction something might appear here - if it's desired behavior i would suggest this way.
If you have several sets of controls apperaing always in the same groups you might consider using QStackedWidget, that allows you to create those widgets already at design stage and swich between groups at runtime.

Related

QLayout and discrete widget representation - how to?

Lets, for example, we have QHBoxLayout inside QMainWindow.
Lets we have set of the widgets inside above layout.
But (!) few of widgets have discrete visual representations.
In another words they have few states dependent on available space.
For example:
if there are too much available space - it must look like big image + some text
if there available minimal space - it must look like little image
if there available few more than minimal space - it must look like button + label
etc...
So when the user change the main window size our "dynamic" widgets must show own representation dependent on available space.
How it could be achieved in Qt?
UPD: the closest behavior present in the Microsoft ribbon interface
UPD2: the QML closest behavior present in gif below (on part where window resized by user)
UPD3: more complex example - each panel in the menu panel change content elements view and count that depends from available space
There's no magic solution for this. You'll need to implement events/actions to take when the container is resized. It can be as simple or complex as you need. There are several different ways to go about actually implementing it, depending on complexity and scope involved (it is just a few items? the whole UI? etc...).
Here is a very basic (crude but effective) example which moves a toolbar to either be on the same line as another toolbar (for wider window) or to its own line (for narrower window). MdiChild in this case is a QWidget implementation which, obviously, contains other widgets and manages their layout.
void MdiChild::resizeEvent(QResizeEvent * event)
{
QWidget::resizeEvent(event);
if (size().width() > ui->topToolbarLayout->sizeHint().width() + ui->botToolbarLayout->sizeHint().width() + 30) {
ui->botToolbarLayout->removeWidget(modelsToolbar);
ui->topToolbarLayout->insertWidget(1, modelsToolbar);
}
else {
ui->topToolbarLayout->removeWidget(modelsToolbar);
ui->botToolbarLayout->insertWidget(0, modelsToolbar);
}
}
As you can see it has to take the container size into account, and the most direct way to do that is in the QWidget::resizeEvent(). You could do anything here you want... change text buttons to icons, hide/show/move stuff... whatever.
Instead of handling the visual changes in the container, you could of course hook up signals/slots to the contained widgets... eg. a custom signal emit availableSizeChanged(QSize size) from the resizeEvent() handler connect()ed to the contained widget(s).
You may find QStateMachine handy to maintain visual state in a formal manner (this is what QML uses for it's state[s] property and transition system).
You could also implement your own QLayout as others have suggested. Though the scope of the question itself suggests you may not need to. The question is quite general IMHO. The two examples provided have massive differences in terms of complexity.
For this answer, I will use Qt-equivalent terms, not the official MS Ribbon terminology.
An Overview
You are actually looking at a number of layouts, in a pattern like so:
QToolbar
| (Layout)
+--> QGroupBox/QToolButton
| | (Layout)
| +----->Button
| +----->Button
+--> QGroupBox/QToolButton
The Pattern
Let's start with just the QGroupBox that populates helps sort our buttons into groups.
Consider that our group box may hold both our dynamic QToolButton and regular widgets. When the available space shrinks, the layout:
Calculates the minimum space required for fixed-sized widgets and the minimumSizeHint() values of the widgets without fixed size policies.
Apportions the remaining space based on the growth policy of each widget.
However, our dynamic tool button may or may not change size depending on available space.
Now we have to start checking if the children of the layout are dynamic or not, using qobject_cast.
When we find a dynamic button, we have to determine if it can shrink or not. If it does, we cache this and its preferred, smaller size.
If it's going to shrink, we have to recalculate our minimum size.
And then we have to keep going, hoping that shrinking the buttons during resize doesn't cause any tricky tie-breakers.
Tie breakers: if two buttons can collapse to a smaller size, which one goess first? We have to account for that, too. Also, MS uses rows of three buttons. We can't collapse one from Qt::ToolButtonTextBesideIcon to Qt::ToolButtonIconOnly, we have to collapse a set of three.
Three horizontal buttons can collapse to three vertical buttons. This, too, needs to be calculated and cached.
There is hope.
We can simplify by making each container only able to hold dynamic tool buttons. Then we don't have to deal with tricky issues like fixed sized widgets and we only need to deal with one type of widget.
Microsoft has also helpfully implemented this behavior for us. You can learn a lot about the behavioral constraints of your layout and child widgets by empirical observation. When do groups collapse? If a group collapses, do other groups expand to take up the space? (The answer to that is no, by the way.) How do buttons group together as they collapse? Are some special in how they collapse and expand (constraints on their expansion and collapsing behavior)?
Qt has also implemented several layouts for us to study and get an idea of how they work and how they are different. QGridLayout is a promising basis, particularly if you do some math to change the row span of widgets on the fly (this is for grouping buttons as they collapse from vertical layout to sets of three horizontal buttons).
In Summary
Completely answering your question is far too broad to be on-topic on SO, but I hope this info guides you where you need to go.

wxWidgets - Sizer disable auto layout

Quite new to wxWidgets and ran into an issue with sizers, in my program I got quite a few buttons in a custom panel which I would like to add a horizontal scrollbar too. However the different sizers that I've tried all got auto layout which re-arranges my buttons upon start and change the distance between them while resizing, I would like to disable all of this behaviour but can't find any documentation on how to do so. Is it not possible or have I just been going about this the wrong way?
If you use sizers, you should let them manage the layout, of course.
You can use absolute positions if you really want to, but this is strongly not recommended and will not allow you to create the layouts that work in all configurations. But if you do decide to do this (again, you really shouldn't), then you wouldn't be using sizers at all.

Drawing Controls Guidelines?

I was wondering how Qt does all its styling. I need to create a custom control and I'd like for it to meet the standards such that my control won't feel out of place on different platforms and styles.
For example, I'm going to need a cursor that's used in text, does Qt provide a method for drawing it? And how would I go about implementing it such that I don't redraw the entire widget for the blinking of the cursor?
What you typically do to create custom widgets is two-folded:
combine existing widgets
derive from existing widgets
That means, e.g., if you want to create a custom text input widget, use an existing one and only change the parts you need to change in overloads. Or maybe your customization does not need to change the text input part at all, but just plug it in at the right place. The widget I am talking about right now is QLineEdit. It is actually very basic and customizable.
There actually exist two methods (at least) on how to combine widgets to form your custom one. The first is to create a .ui file and use it in your custom class (or create widgets in code). The second one is to use a QGraphicsScene. There you can combine freehand painting (QPainter), with customly positioned objects and fully-fledged widgets.
If it is too hard to solve your problem by combining widgets and/or deriving from them, the last resort is always to take an existing widget with the desired functionality (e.g. QLineEdit that has a text-edit cursor) and read/copy the code (Note: license issues may arise).
To give a better answer to your question we would need more details on what exactly you want to achieve.

What makes a Qt widget and its layout behave properly (in regard to its size)?

I'm having all sorts of size problems with Qt. I am creating my own widgets and using different layouts (generally, I need my own to make them work properly without spending hours on the "powerful" default layouts... which don't lay things out as intended.)
Once I'm done with a widget and its layout though, it doesn't work right. The size is never getting set properly unless I call widget->resize(1, 1); which finally forces a "resize" and makes the widget look correct (i.e. recompute the geometry.) Even the updateGeometry() call has no effect.
This is a dreadful problem when the resize() needs to be called on the parent widget (yuck!) and from what I'm reading should not be necessary were the layouts properly programmed.
Is there a sample that works and is not several thousand of lines long, or does Qt require several thousand lines to make anything work perfectly, even the simplest widget?
What are the minimal functions to be called to make a widget & its layout work at once?
Thank you.
Alexis
P.S. I tried to implement the sizeHint(), minimumSize(), maximumSize(), others that I'm missing? I was hoping that would be enough. Obviously, I also implement the setGeometry() on the layout to resize the children appropriately.
--- addition 1
There is a sample image with a layout that clearly isn't available as is in Qt. The positioning, functions, and colors of the different keys is XML driven and works for any keyboard in the world.
(note, this sample doesn't show the Enter key displayed on two rows and wider below than at the top; more or less, not doable at all with the regular layouts; of course, it works with my version.)
--- clarification
I'm not too sure how to describe the problem better. I was thinking to write a test widget next to see how I can reproduce the problem and then post that and eventually fix it. 8-)
The default layout function that the internal Qt layouts make use of require a lot of coding. I would like to avoid having to copy/paste all of that because for maintenance, it makes it close to impossible.
--- today's findings
As I needed to tweak one of the widgets, I decided to add a VBoxLayout and make it work.
I actually found the problem... One of the widgets in my tree is a QScrollArea and that sizeHint() returns (-1, -1). Not exactly what I'd expect but... whatever you put inside that widget has better know how to compute its width and height or else... it fails.
Looking at the code closely, I could actually compute the width by using the widest width found. Once I used that, the widget would appear (and it actually resizes itself as things change in the list, kinda cool.)
This being said, my earlier comment about having a tree of widgets that auto-resize themselves stands. From the root up to the parents of the leaves in your tree, all of those widgets will need a valid layout. Once I added one in the top widget it resized itself and its children properly (well... in my case up to the QScrollArea, the rest required a bottom to top resizing. Funny how that works!)
--- ah! ha! moment (or: what you find reading the implementation code!)
Today I bumped in another problem which just needed the correct call... I just couldn't find anything worth it in the documentation.
All the objects have a layout now, but a certain parent would not resize properly. Plain simple.
I had a call to the parent as following:
// changes to the children are changing the geometry
parentWidget()->updateGeometry();
Yeah. The docs says that's what you have to do. Nothing happens at all with that call. No idea what it's supposed to do, I did not look at that function. It never did anything for me anyway.
So... I looked at the layout to try to understand how it would send the info up/down. I did not see much except for one interesting comment:
// will trigger resize
This is said of the SetFixedSize mode. To reach that function you need to make the layout for update. Ah! Yes... the layout, not the parent widget... let's try that instead:
parentWidget()->layout()->update();
And voila! It resizes correctly in all cases I have. Quite incredible that the widget updateGeometry() doesn't trigger the same effect...
Although it's possible to do what you want it sounds like the problems you are having are because you're using Qt in a way that it's not meant to be used. Why do you need separate widgets for each key represented on the keyboard?
I see two options, both of which are better in some way:
Use QGraphicsScene and QGraphicsView.
A single custom widget that uses custom drawing to display the keyboard (and likely uses hover for hints).
The first option is probably better. Your keys could then be represented by QGraphicsSimpleTextItem's or even a QGraphicsSvgItem. It also provides a number of standard layouts or you could choose to write your own layout. By default you can use the keyPressEvent or mouseReleaseEvent to respond to user interactions.
I'd highly recommend you take a look at the QGraphicsView examples to get an idea what you can do.
If you go the second route you'll need to record the different key locations so you can respond accordingly as the user moves the mouse around, clicks, etc.
This won't help you with your immediate issue but I wanted to show you a keyboard I made using standard layouts and buttons. It's not perfect and it still won't help you with an enter key that spans two rows but it's not bad. It's resizable too by resizing the window, although I'm not sure if that will be apparent from the images below as SO may be scaling them. (you can view the actual images by opening them in their own tab)
Anyway, this was done using only Qt Designer with no manual coding. It consists of a top level vertical layout with 5 horizontal layouts in it. The buttons are then inserted into one of the 5 horizontal layouts. The size of the keys can be controlled by setting the horizontal and vertical size policies to "ignored" for most of the buttons and then horizontal "minimum" for buttons that you want to be wider. Things can be tweaked by setting min and max size restrictions to buttons. When resized, the buttons will not maintain their relative proportions though, that would probably take some custom programming.
The styling in your example could be approximated pretty well using css style sheets and background images. Still not a minor effort but you should be able to get most of the way there without custom layouts and buttons.

How to make a QT widget update modified properties from its parent widget?

I've got a QWidget that contains several QLineEdits. When I tell the parent QWidget to change its background color
dynamically, I'd like the children (i.e. QLineEdits) to inherit this modification.
Is there an easy (read: one function call) to do this?
If nothing pops up, I think I'll just loop through the children of the QWidget, but when doing this properly I expect to end up with a recursive function with a lot of overhead, that's why I'm asking.
EDITs in Bold face.
Generally speaking you don't need to worry about "overhead" in dialogs. Unless you're doing some sort of massive draw operation, UI applications simply don't need a lot of optimizations. Digging down to all children and changing their background is a relatively fast operation compared to the Qt system itself actually doing the change.
That said, I'd assume there is a way to get what you want but I don't know what it is. My bet is that it will do exactly what you would anyway.
How are you going about telling it to "change color" btw? Qt doesn't seem to have operations to do that. You can assign a background role or change the pallete. As to the latter:
http://doc.qt.nokia.com/4.7/qwidget.html#palette-prop
If you set the background color using a style sheet assigned to that widget and don't specify any selectors in the CSS, all child widgets will inherit any properties that apply to them.
I found it useful to use a selector that allowed me to target specific widgets for a certain style.
QWidget[objectName|="special_color"]
{
color: rgb(255, 255, 255);
}
If I used this in a style sheet assigned to a container widget, it would apply the specified color to any child widgets whose name started with "special_color" like "special_colorEditBox1" no matter how they are nested or contained.