Qt World Summit: Register Today!

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;
    datalayout = new QGridLayout;

    QLabel* field[5];
    for(int j = 0; j < 4; j++)
        field[j] = new QLabel("test " + j);

    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:
    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) {


    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));

  • Moderators

    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.

Log in to reply