向Qlistview的项目添加图标

时间:2019-07-04 22:26:38

标签: python pyqt icons pyqt5 qlistview

直接解决这个问题,我想在Qlistview的项目中添加图标。我一直在尝试setData,但没有成功。

代码:

import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        iconroot = os.path.dirname(__file__)
        self.setFont(QtGui.QFont("Helvetica", 8, QtGui.QFont.Normal, italic=False)) 
        lay = QtWidgets.QVBoxLayout(self)

        self.listView = QtWidgets.QListView()
        lay.addWidget(self.listView)

        self.entry = QtGui.QStandardItemModel()
        self.listView.setModel(self.entry) 
        self.listView.setSpacing(5)

        for text in ("One", "two", "Three", "Four", 
                     "Five etc.."):
            it = QtGui.QStandardItem(text)
            self.entry.appendRow(it)
            it.setData(QtGui.QIcon(iconroot +'/images/flags'),QtCore.Qt.DecorationRole)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

希望像这样。

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试一下:

import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

#        iconroot = os.path.dirname(__file__)

        self.setFont(QtGui.QFont("Helvetica", 8, QtGui.QFont.Normal, italic=False)) 
        lay = QtWidgets.QVBoxLayout(self)

        self.listView = QtWidgets.QListView()
        lay.addWidget(self.listView)

        self.entry = QtGui.QStandardItemModel()
        self.listView.setModel(self.entry) 
        self.listView.setSpacing(5)

#        for text in ("One", "two", "Three", "Four", 
        for i, text in enumerate(["One", "two", "Three", "Four",                          # +++
                                  "Five etc.."]):
            it = QtGui.QStandardItem(text)
            self.entry.appendRow(it)

#            it.setData(QtGui.QIcon(iconroot +'/images/flags'), QtCore.Qt.DecorationRole)
            it.setData(QtGui.QIcon(os.path.join('images', 'bao{}.png'.format(i))),        # +++
                                   QtCore.Qt.DecorationRole)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

enter image description here