How to display Images in QListView
Hi i am trying to display images in the ListView,
I am new to Model View Delegate programming and i am trying to learn using that, i am getting a plain window with out images.
Here is my code
Header File:
Code:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QDir>
#include <QList>
#include <QDebug>
#include <QFileDialog>
#include <QStringListModel>
#include <QListView>
#include <QSortFilterProxyModel>
#include <QStandardItemModel>
namespace Ui {
class Widget;
}
{
Q_OBJECT
public:
explicit Widget
(QWidget *parent
= 0);
~Widget();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
CPP File:
Code:
#include "widget.h"
#include "ui_widget.h"
ui(new Ui::Widget)
{
ui->setupUi(this);
QDir directory
("/u03/Commom_SelfDiag/BackUp/CSD_Tool/");
const QString folderPath
= directory.
filePath("images/");
if(!folderPath.isEmpty())
{
dir.setNameFilters(filter);
QFileInfoList filelistinfo = dir.entryInfoList();
foreach
(const QFileInfo &fileinfo, filelistinfo
) {
thumbnails << fileinfo.absolutePath();
}
}
int count = thumbnails.count();
qDebug()<<"The Total Images are"<<count;
model->insertColumn(0);
const int numRows = thumbnails.size();
model->insertRows(0,numRows);
for(int i=0;i<numRows ;++i)
{
model
->setData
(model
->index
(i,
0),
QPixmap(thumbnails.
at(i
)),Qt
::DecorationRole);
}
proxyModel->setSourceModel(model);
proxyModel->setFilterKeyColumn(0);
galleryView
->setViewMode
(QListView::IconMode);
galleryView->setModel(model);
ui->horizontalLayout->addWidget(galleryView);
}
Widget::~Widget()
{
delete ui;
}
Main File
Code:
#include <QtGui/QApplication>
#include "widget.h"
int main(int argc, char *argv[])
{
Widget w;
w.show();
return a.exec();
}
Me and my friend are trying this example and we are trying the QStandardItemModel but we are unable to solve.
Please make necessary changes to make the code execute by displaying images.
Re: How to display Images in QListView
How do you know that you are actually loading the images into QPixmap? You don't do any error checking at all on this line of code:
Code:
model
->setData
(model
->index
(i,
0),
QPixmap(thumbnails.
at(i
)),Qt
::DecorationRole);
You just assume the QPixmaps are loaded and stored in the model. Break this line of code into two lines and check that you actually have a valid pixmap before storing it in the model:
Code:
QPixmap pixmap
( thumbnails.
at( i
) );
if ( !pixmap.isNull() )
model->setData( model->index(i,0), pixmap, Qt::DecorationRole);
else
qDebug() << "Failed to load pixmap from file: " << thumbnails.at( i );