Pratik Singhal
Pratik Singhal

Reputation: 6492

Why are File Icons not visible in QListView?

I have a QListView in my application and want to display a list of files with their icons as shown in the QT Documentation.
QListView is in the Icon mode I have the following code :-

std::vector<std::string>::iterator it = result.begin() ; // got the results, now tie them to the StandardItemModel. 
        RespPara::stringList = new QStringList ; 
        RespPara::model = new QStringListModel ; 
        while(it!=result.end())
          {
        std::cout<<*it<<std::endl ;
        RespPara::stringList->append((*it).c_str()) ; 
        it++ ; 
          }
        RespPara::model->setStringList(*(RespPara::stringList)) ; 
        RespPara::mainWindow->listView->setModel(RespPara::model) ;

Now, although the list of files is visible in the main application, the icons are not visible.
What am I doing wrong here? How can I correct this problem?

EDIT :- Here is the new code which is giving the same icon for all types of files :-

    while(!in.eof())
    {
      getline(in, buff) ; 
      QFileInfo fileInfo(buff.c_str()) ; 
      QFileIconProvider iconProvider  ; 
      QIcon icon = iconProvider.icon(fileInfo) ;
      QStandardItem* standardItem = new QStandardItem(icon, buff.c_str()) ; 
      myModel->appendRow(standardItem)  ;
    } 
  win.listView->setModel(myModel) ; 

Here is the screen shot :-

enter image description here

enter image description here

Upvotes: 0

Views: 1129

Answers (1)

Tay2510
Tay2510

Reputation: 5978

QListView is not that powerful to recognize the file icon, it's merely a listview. If you'd like to display icons in QListView, the conventional way is to instantiate a QIcon and set it to your model, for example:

QIcon icon(":/myIcons/theIcon.png");
model->setItem(0,0, new QStandardItem(icon, "Text next to the icon"));

There is no any icon set in your code, that's why you can't see them.

In your case, the QIcon should be provided by file icon and you have to seek help from QFileIconProvider class. The following code get the file icon from your system:

QFileInfo fileinfo("C:/cat/is/lovely/Test.txt"); // Provides the information of file type
QFileIconProvider iconprovider;
QIcon icon = iconprovider.icon(fileinfo); // return QIcon according to the file type

After that, you set the QIcon on your model.

enter image description here

Upvotes: 3

Related Questions