我有一个可以动态创建QLabel的应用程序,以显示文件夹中存在的不同数量的图像。
以下是我用来创建这些标签的代码:
// 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;
我想使用鼠标单击选择多个这些图像并删除所选图像。有人可以帮我吗?
前进的道路可能是准备某种容器,以保留处理点击事件所需的所有必要信息。例如,您可以使用列表保留选择的标签,并在再次单击时删除单击的窗口小部件。实际上,您可以随意使用单击的项目,但是问题是要获得单击的项目。该草案可以帮助:
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可能是一个方便的选择。但是,可能需要对布局系统进行一些重构。