【问题标题】:How to select multiple QLabel objects using mouse click?如何使用鼠标单击选择多个 QLabel 对象?
【发布时间】:2019-12-17 12:56:44
【问题描述】:

我有一个应用程序可以动态创建 QLabels 以显示文件夹中存在的不同数量的图像。

以下是我用来创建这些标签的代码:

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

我想使用鼠标单击选择多个这些图像并删除选定的图像。 有人可以帮我吗?

【问题讨论】:

  • 您是想通过单击来累积选择,还是想要橡皮筋选择之类的东西?
  • 顺便说一句。如果你会使用例如QTableWidget 作为图像的容器或类似的东西,然后你会得到“免费”的选择。
  • 我想通过单击来累积选择

标签: c++ linux qt5 qlabel


【解决方案1】:

前进的方向可能是准备某种容器来保存处理点击事件所需的所有信息。 例如,您可以使用列表来保留选定的标签并在再次单击时删除单击的小部件。 实际上,您可以随心所欲地处理点击的项目,但问题是获得点击的项目。此草稿可以提供帮助:

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
        }
    }
}

如果您有足够的时间,您可以在 Qt 文档中寻找更可靠和原生的选项。例如,正如 Scheff 注意到的那样,QTableWidget 可能是一个方便的选择。但是,它可能需要对您的布局系统进行一些重构。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-01
    • 2012-08-14
    • 1970-01-01
    • 2014-07-08
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    • 2023-04-01
    相关资源
    最近更新 更多