Populating a Grid with buttons but having problems
-
So i have a Grid that i want to populate with buttons that has icons of the images found in a folder! now that works and is fine but everytime i upload a new image i want to run this function but that means that it will duplicate everything each time!
so i need to remove everything in
ui->GRID_IMAGEFOLDER_DISPLAY
and then repopulate it! but how todo the removing part?void MainWindow::updateImageFolder() { QDir directory("./Matrix Images/32 x 32/"); QStringList images = directory.entryList(QStringList() << "*.png" << "*.PNG",QDir::Files); for(int i = 0; i < images.count(); i++) { // figured i do the removing / deleting here befor repopulating } foreach(QString filename, images) { QPushButton *button = new QPushButton(this); //connect(button, SIGNAL(clicked()), this, SLOT(mySlot())); button->setMinimumSize(32, 32); button->setMaximumSize(32, 32); button->setFixedSize(32, 32); button->setIcon(QIcon("./Matrix Images/32 x 32/" + filename)); button->setIconSize(QSize(32, 32)); button->setCursor(Qt::PointingHandCursor); button->setObjectName(filename); ui->GRID_IMAGEFOLDER_DISPLAY->addWidget(button); } }
-
@Kris-Revi
To undo your previousaddWidget(button)
s, you need to take the button out of the layout and delete it cleanly. One way is to use [override virtual]QLayoutItem *QGridLayout::takeAt(int index) with the code like in https://doc.qt.io/qt-5/qlayout.html#takeAt:QLayoutItem *child; while ((child = layout->takeAt(0)) != nullptr) { ... delete child->widget(); // delete the widget delete child; // delete the layout item }
Note that your proposed loop through the images found in the folder to do the deleting of the buttons with images previously created is not a good approach: if an image file has been deleted you will not meet it in that new loop now to delete it, you want to iterate through the widgets already in the layout doing deletions as per my suggestion.
Of course it's not very efficient if you have to recreate all the old items in response to "everytime i upload a new image i want to run this function ", if you want that "nicer" you'd have to add/remove only the changed icons in the folder, but that's up to you....