PDA

View Full Version : Place widgets at specific position



Thibaut
27th May 2020, 14:05
Hi!

I have a very quick question.

To make things simple, the data my users will load will have some sort of events at specific time.
Each of this event is associated with a code.
I'm already able to draw a vertical line at the time of the event, and now, I want to display those codes on top of my plot at the specified time, above the lines.

Here's what I have for now:


void EventLabels::displayEvents(QVector<QVector<int>> eventToDisplay)
{
// eventToDisplay:
// Event Position | Event Code

for (int i = 0; i < eventToDisplay.length(); i++)
{
QLabel *eventCode = new QLabel;
eventCode->setText(QString::number(eventToDisplay[i][1]));

eventCode->setParent(this);

eventCode->move(eventToDisplay[0][1], 0);
}
}


I have to note that this function is a slot that receive data from another class. As the user can change the displayed data, the codes will change too each time the user push a button.
From what I find, this seems to be the best solution to precisely place QWidgets at specific position.
Did I miss something or is there a better way to do it?

d_stranz
27th May 2020, 16:07
It is usually never a good idea to place widgets at fixed locations. What happens when the user decides to resize the window? All of your labels are locked in position relative to the top left corner of the parent widget, so they won't move and will now be in the wrong places. Because you create them without storing their pointers anywhere (except as children of the parent widget), it is difficult to retrieve them and move them to the correct positions.

If this was my problem, I would make a custom QWidget with a paintEvent method. In the paintEvent, you calculate the positions of where your labels should be based on the current size of the widget, and draw them using QPainter::drawText(). Don't use QLabels as child widgets at all. If you use this custom QWidget correctly and put it inside of a layout, it will be resized (and repainted) automatically when the size changes. Simply store your vector of text locations as a member variable of this class, and add a slot to update it when the user changes the labels.