Naman Lazarus
Naman Lazarus

Reputation: 53

How to select multiple QLabel objects using mouse click?

I have an application which dynamically creates QLabels to display different number of images present within a folder.

Following is the code that I used to create those labels:

    // dynamically displaying images
int n = 0;
int row = 0;
while (row >= 0) {
    for (int col = 0; col < 4; col++) {
        if (n < noOfImagesInSkippedFolder) {
            // image exists
            intToString = to_string(n);
            cout << skippedImageName << endl;
            QLabel *labelName = new QLabel();
            labelName->setFixedHeight(100);
            labelName->setFixedWidth(100);
            labelName->setStyleSheet("background-color: rgb(255, 255, 255); border: 1px solid rgb(60, 60, 60);");

            imageToDisplay = imread("bin/skippedAkshars/" + intToString + ".jpg", CV_LOAD_IMAGE_GRAYSCALE);

            QImage srcImage = QImage(imageToDisplay.data, imageToDisplay.cols, imageToDisplay.rows, imageToDisplay.step, QImage::Format_Grayscale8);
            int w = labelName->width();
            int h = labelName->height();
            labelName->setPixmap(QPixmap::fromImage(srcImage).scaled(w,h, Qt::KeepAspectRatio));

            ui->gridLayout->addWidget(labelName, row, col);
            n = n + 1;
        }
        else { // images does not exist
            goto done;
        }
    }
    row++;
}
done:
cout << "done!" << endl;

I would like to select multiple of these images using mouse click and delete the selected images. Can someone please help me with this?

Upvotes: 0

Views: 426

Answers (1)

Arman Novikov
Arman Novikov

Reputation: 46

The way forward may be to prepare some kind of a container for keeping all necessary info to process click events. For example, you can use a list to keep choosen labels and remove the clicked widget if it is clicked again. Actually, you can do with the clicked items whatever you want, but the issue is to get a clicked item. This draft can help:

void MainWindow::mousePressEvent(QMouseEvent *event)
{
https://doc.qt.io/qt-5/qwidget.html#mousePressEvent for details
    QWidget * const widget = childAt(event->pos());
    qDebug() << "child widget" << widget;
    if (widget) {
        const QLabel * const label = qobject_cast<QLabel *>(widget);
        if (label) {
            qDebug() << "label" << label->text();
            // here a clicked ("selected") label can be handled
            // like capturing its ref, obscuring and etc
        }
    }
}

If you have enough time you can look for more solid and native options in Qt documentation. For example, as Scheff has noticed QTableWidget can be a handy option. However, it may require some refactoring for your layout system.

Upvotes: 1

Related Questions