【Pyqt实例16】自定义model

# -*- coding: utf-8 -*-

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys

QTextCodec.setCodecForTr(QTextCodec.codecForName("utf8"))

class StringListModel(QAbstractListModel):
    def __init__(self,strings,parent):
        super(StringListModel,self).__init__()
        self.stringList = strings
        self.headerData(0,Qt.Horizontal)
        self.value = 0
    
    def rowCount(self,parent):
        return self.stringList.count()
                
    def data(self,index,role=Qt.DisplayRole):
        if index.isValid() is False:
            return QVariant()
        if index.row() >= len(self.stringList):
            return QVariant()
        if role == Qt.DisplayRole:
            return self.stringList[index.row()]
        else:
            return QVariant()
    
    def headerData(self,section,orientation,role=Qt.DisplayRole):
        if role != Qt.DisplayRole:
            return QVariant()
        if role == Qt.DisplayRole or orientation == Qt.Horizontal:
            return QString("Column %1").arg(section)
        else:
            return QString("Row %1").arg(section)
        
    def flags(self,index):
        if index.isValid() is False:
            return Qt.ItemIsEnabled
        return Qt.ItemIsEnabled|Qt.ItemIsEditable
    
    def setData(self,index,value,role=Qt.EditRole):
        if index.isValid() or role == Qt.EditRole:
            try:
                self.stringList.replace(index.row(),value)
            except:
                self.stringList.replace(index.row(),value.toString())
            self.dataChanged.emit(index,index)
            return True
        return False
    
    def insertRows(self,position,rows,index):
        self.beginInsertRows(QModelIndex(),position,position + rows - 1)
        for i in xrange(rows):
            self.stringList.insert(position,"")
        self.endInsertRows()
        return True
    
    def removeRows(self,position,rows,index):
        self.beginRemoveRows(QModelIndex(),position,position + rows - 1)
        for row in xrange(rows):
            self.stringList.removeAt(position)
        self.endRemoveRows()
        return True

class MainWindow(QMainWindow):
    def __init__(self,parent=None):
        super(MainWindow,self).__init__()
        self.name = QString()
        self.strList = QStringList()
        
        self.createActions()
        self.createMenus() 
        self.setupModel()
        self.setupView()    
        
    def createActions(self):
        self.myaction = QAction(self.tr("打开"),self)
        self.connect(self.myaction,SIGNAL("triggered()"),self.slotOpenFile)
    
    def createMenus(self):
        PrintMenu=self.menuBar().addMenu(self.tr("文件"))
        PrintMenu.addAction(self.myaction)  
        circumgyrateMenu=self.menuBar().addMenu(self.tr("编辑"))

    def setupModel(self):
        #self.model = QStandardItemModel(4,4)
        self.model = StringListModel(self.strList,self)
    
    def setupView(self):
        self.list = QListView()
        self.list.setModel(self.model)
        self.setCentralWidget(self.list)
    
    def slotOpenFile(self):
        self.name = QFileDialog.getOpenFileName(self,"open file dialog",".","strip file(*.txt)")
        if self.name.isEmpty() is False:
            self.openFile(self.name)
    
    def slotSaveFile(self):
        if self.name.isEmpty():
            return
        file = QFile(self.name)
        if file.open(QFile.WriteOnly):
            return
        ts = QTextStream(self.file)
        for i in xrange(self.model.rowCount()):
            index = self.model.index(i)
            str = self.model.data(index).toString()
            ts << str << ","
    
    def openFile(self,path):
        if not path.isEmpty():
           file = QFile(path)
           if file.open(QFile.ReadOnly|QFile.Text):
              stream = QTextStream(file)
              line = stream.readLine()
              if line.isEmpty() is False:
                 pieces = line.split(",",QString.SkipEmptyParts)
                 row = 0
                 for i in pieces:
                    self.model.insertRows(row,1,QModelIndex())
                    self.model.setData(self.model.index(row),i)
                    row+=1                  
           file.close()
        
    def slotInsertRows(self):
        ok = True
        index = self.list.currentIndex()
        rows = QInputDialog.getInteger(self,self.tr("Insert Row Number"),self.tr("Please input number:"),1,1,10,1,1,ok)
        if ok:
            self.model.insertfRows(index.row(),rows,QModelIndex())
    
    def slotRemoveRows(self):
        index = self.list.currentIndex()
        self.model.removeRows(index.row(),1,QModelIndex())
    
app=QApplication(sys.argv)
window=MainWindow()
window.show()
app.exec_()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值