Clicking And Draging A QLabel That Is Created Dynamically (at runtime)

  • I have an application which needs to create qlabels at runtime.

    To keep things simple we will just deal with one label all though the app will create as many as needed.

    How can I add code that will allow me to click and drag this label somewhere else on the screen?

    void MainWindow::on_cmdCreateLabel_clicked()
    QLabel* lbl;
    lbl = new QLabel("test ", ui->grpLabels);
    lbl->setGeometry(10, 20 + 20, 100, 18);
    lbl->setStyleSheet("QLabel { background-color : black; color : red; }");

  • Moderators


    What is the purpose of dragging the labels around?

    QLabels are designed to be stationary. Would the "Graphics View Framework": or "Qt Quick": suit your use case better?

  • It doesnt have to be labels. I just need to be able to write text in them.

    The key that I have yet to figure out is how to add what i call (event handlers from windows programming) that will capture the drag drops when the objects are created dynamically at runtime.

  • Moderators

    See the links I posted. They show you how to implement drag and drop in the Graphics View Framework and in Qt Quick.

    Also please describe what you want to do with the draggable labels, and how you want them to interact with the other components of your program. Your answer will influence the best way to implement this.

  • I appreciate the input. I have been reading over the robot example for the past few days and to be honest, it is quite complex (at least for what I am trying to do)

    Basically I am trying to create an application that has a few predefined products and the user can drag them to see what they look like visually when put together.

    I was using labels because i found this code which allows you to load images
    QPixmap pix("C:\your_image.jpg");
    ui->label_3->setPixmap(pix.scaled(500, 500,
    Qt::KeepAspectRatio, Qt::SmoothTransformation));@

    At the moment I am looking at the qt quick example but this seems very similar to XAML which is much different then the 'win forms' im use to (my background is c# but I am trying to learn QT/C++)

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.