2014-06-14 14 views
0

我在我的應用程序中有一個QListView,並希望顯示一個帶有圖標的文件列表,如QT文檔中所示。
而QListView是在Icon mode 我有下面的代碼: -爲什麼文件圖標在QListView中不可見?

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) ; 

現在,雖然文件列表是在主應用程序可見,該圖標是不可見的。
我在這裏做錯了什麼?我該如何糾正這個問題?

編輯: - 這裏是一個被賦予了相同的圖標爲所有類型的文件的新代碼: -

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) ; 

下面是截圖: -

enter image description here

enter image description here

+0

您是否在'buff'中包含文件擴展名(例如:.txt)? – Tay2510

+0

是的,我已經包含了它 –

+0

什麼是「相同的圖標」?截圖可能? – Tay2510

回答

3

QListView是不是很強大的識別文件圖標,它只是一個列表視圖。如果您想在QListView顯示圖標,傳統的方法是實例化一個QIcon並將其設置爲你的模型,例如:

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

有沒有在你的代碼中設置的任何圖標,這就是爲什麼你可以看不到他們。

在你的情況下,QIcon應該由文件圖標提供,你必須從QFileIconProvider類尋求幫助。下面的代碼從系統中獲得的文件圖標:

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 

之後,您會在您的模型QIcon

enter image description here

+1

此外,它是值得實現自己的模型類,以便您只需要獲取可見的文件圖標(您可以緩存) – Pete

+0

好吧,但還有一個問題,ListView顯示每個文件類型相同的圖標,而不是顯示不同文件類型的不同圖標 –

+0

@ ps06756你可以告訴我代碼嗎?在我的演示中,它確實顯示了不同文件類型的不同圖標。 – Tay2510