QTableWidget
我需要从目录中放入图像并检索所选单元格中的图像名称。如何根据目录中的文件数自动生成行数和列数?我可以手工将图像添加到表格中,但这不是我想要做的。我想它必须是的东西
QDir dir("images/");
QFileInfoList dirContent = dir.entryInfoList(QStringList()<< "*.png", QDir::Files |
QDir::NoDotAndDotDot);
但我仍然无法知道如何做到这一点。
答案 0 :(得分:3)
有两种方法。
#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
答案 1 :(得分:2)
QFileInfoList
只是QList<QFileInfo>
,因此您可以轻松获得此列表的大小。使用这样的东西:
QDir dir("G:/2");
QFileInfoList dirContent = dir.entryInfoList(QStringList()<< "*.png", QDir::Files |
QDir::NoDotAndDotDot);
ui->tableWidget->setColumnCount(1);
ui->tableWidget->setRowCount(dirContent.size());
for(int i=0; i < dirContent.size(); i++)
{
qDebug() << dirContent.at(i).absoluteFilePath();
ui->tableWidget->item(i,0)->setData(Qt::DecorationRole, QPixmap(dirContent.at(i).absoluteFilePath()));
}
您也可以使用scale()
方法缩放图片并使用:
ui->tableWidget->resizeRowsToContents();