有两种方法。
非递归
主文件
#include <QDir>
#include <QFileInfo>
#include <QTableWidget>
#include <QPixmap>
#include <QApplication>
int main(int argc, char **argv)
{
QApplication application(argc, argv);
QTableWidget tableWidget(100, 5);
QDir dir("images/");
for (const auto& fileInfo : dir.entryInfoList(QStringList{"*.png"}, QDir::Files | QDir::NoDotAndDotDot))
{
static int row = 0, column = 0;
QTableWidgetItem *newItem = new QTableWidgetItem(QObject::tr("%1").arg((row+1)*(column+1)));
newItem->setData(Qt::DecorationRole, QPixmap(fileInfo.absoluteFilePath()));
tableWidget.setItem(row, column, newItem);
if (column == tableWidget.columnCount()) {
column = 0;
row++;
}
}
tableWidget.show();
return application.exec();
}
主程序
TEMPLATE = app
TARGET = main
QT += widgets
CONFIG += c++11
SOURCES += main.cpp
构建并运行
qmake && make && ./main
递归的
主文件
#include <QDir>
#include <QDirIterator>
#include <QFileInfo>
#include <QTableWidget>
#include <QPixmap>
#include <QApplication>
int main(int argc, char **argv)
{
QApplication application(argc, argv);
QTableWidget tableWidget(100, 5);
QDir dir("images/");
dir.setFilter(QDir::NoDotAndDotDot| QDir::Files);
QDirIterator it(dir, QDirIterator::Subdirectories);
while (it.hasNext()) {
static int row = 0, column = 0;
it.next();
QFileInfo Info = it.fileInfo();
QString path = Info.absolutePath();
if(Info.isFile() && path.endsWith(".png")) {
QTableWidgetItem *newItem = new QTableWidgetItem(QObject::tr("%1").arg((row+1)*(column+1)));
newItem->setData(Qt::DecorationRole, QPixmap(path));
tableWidget.setItem(row, column, newItem);
if (column == tableWidget.columnCount()) {
column = 0;
row++;
}
}
}
tableWidget.show();
return application.exec();
}
主程序
TEMPLATE = app
TARGET = main
QT += widgets
CONFIG += c++11
SOURCES += main.cpp
构建并运行
qmake && make && ./main