Dynamically Adding QLabels At Runtime
-
I have an application that I wont know in advance the number of labels needed and they need to be created and added to the form at runtime.
I have this code but nothing happens. The lables are never added to the form
@
dataGroupBox = new QGroupBox;
//gridGroupBox->setTitle(tr("Buttons"));
datalayout = new QGridLayout;QLabel* field[5]; for(int j = 0; j < 4; j++) { field[j] = new QLabel("test " + j); datalayout->addWidget(field[j],j,1); } dataGroupBox->setLayout(datalayout);@
header looks like this
@ QGridLayout *datalayout;
QGroupBox *dataGroupBox;@Can somwone show me how to dynamically create labels?
-
Your a genius. Thank you for your help!
Do you know how I can move each label with my mouse? I have been trying to get this to work but so far have been unsuccessful.
I searched and found this code but it is more related to moving the form itself and not a dynamic label
Add to window .h file:
@
private:
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
int m_nMouseClick_X_Coordinate;
int m_nMouseClick_Y_Coordinate;
@And this to .cpp file:
@
void MainWindow::mousePressEvent(QMouseEvent *event) {
m_nMouseClick_X_Coordinate = event->x();
m_nMouseClick_Y_Coordinate = event->y();
}void MainWindow::mouseMoveEvent(QMouseEvent *event) { move(event->globalX()-m_nMouseClick_X_Coordinate,event->globalY()-m_nMouseClick_Y_Coordinate); }
@
I also found this code but I am not sure how to attach it to the dynamic labels mouse down/move event
@
void DropLabel::mousePressEvent(QMouseEvent *event)
{
offset = event->pos();
}void DropLabel::mouseMoveEvent(QMouseEvent *event)
{
if(event->buttons() & Qt::LeftButton)
{
this->move(mapToParent(event->pos() - offset));
}
}
@ -
This code uses a subclass of QLabel. You can't just "paste" it anywhere in your code. It's more complicated than that.
This is entirely different topic. Please start a new thread with this question.