qt下listview增加一行数据

qt下listview增加一行数据,第1张

在Qt中,可以使用addItem()函数来增加一行数据到listview中。例如,你可以使用以下语句在listview中添加一行数据:

listView->addItem("1","2","3","4")

import sys

from PyQt4.QtCore import *

from PyQt4.QtGui import *

####################################################################

def main():

app = QApplication(sys.argv)

w = MyWindow()

w.show()

sys.exit(app.exec_())

####################################################################

class MyWindow(QWidget):

def __init__(self, *args):

QWidget.__init__(self, *args)

# create objects

list_data = [1,2,3,4]

lm = MyListModel(list_data, self)

de = MyDelegate(self)

lv = QListView()

lv.setModel(lm)

lv.setItemDelegate(de)

# layout

layout = QVBoxLayout()

layout.addWidget(lv)

self.setLayout(layout)

####################################################################

class MyDelegate(QItemDelegate):

def __init__(self, parent=None, *args):

QItemDelegate.__init__(self, parent, *args)

def paint(self, painter, option, index):

painter.save()

# set background color

painter.setPen(QPen(Qt.NoPen))

if option.state &QStyle.State_Selected:

painter.setBrush(QBrush(Qt.red))

else:

painter.setBrush(QBrush(Qt.white))

painter.drawRect(option.rect)

# set text color

painter.setPen(QPen(Qt.black))

value = index.data(Qt.DisplayRole)

if value.isValid():

text = value.toString()

painter.drawText(option.rect, Qt.AlignLeft, text)

painter.restore()

####################################################################

class MyListModel(QAbstractListModel):

def __init__(self, datain, parent=None, *args):

""" datain: a list where each item is a row

"""

QAbstractTableModel.__init__(self, parent, *args)

self.listdata = datain

def rowCount(self, parent=QModelIndex()):

return len(self.listdata)

def data(self, index, role):

if index.isValid() and role == Qt.DisplayRole:

return QVariant(self.listdata[index.row()])

else:

return QVariant()


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11635790.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-17
下一篇 2023-05-17

发表评论

登录后才能评论

评论列表(0条)

保存