自定义代理

链接:https://pan.baidu.com/s/11JcTC52ZK9ne6mpdRgQSfg 
提取码:vzic

代理文件

from PyQt5.QtWidgets import QStyledItemDelegate
from PyQt5.QtWidgets import QDoubleSpinBox,QComboBox
from PyQt5.QtCore import Qt

##基于QDoubleSpinbox的代理组件
class QmyFloatSpinDelegate(QStyledItemDelegate):
    def __init__(self, minV=0,maxV=10000,digi=2,parent=None):
        super().__init__(parent)
        self.__min=minV
        self.__max=maxV
        self.__decimals=digi

    #自定义代理组件必须实现以下4个函数
    def createEditor(self, parent, option, index):
        editor=QDoubleSpinBox(parent)
        editor.setFrame(False)
        editor.setRange(self.__min,self.__max)
        editor.setDecimals(self.__decimals)
        return editor
    def setEditorData(self, editor, index):
        model=index.model()#关联的数据模型
        text=model.data(index,Qt.EditRole)#单元格文字
        editor.setValue(float(text))
    def setModelData(self, editor, model, index):
        value=editor.value()
        model.setData(index,value,Qt.EditRole)
    def updateEditorGeometry(self, editor, option, index):
        editor.setGeometry(option.rect)

class QmyComboBoxDelegate(QStyledItemDelegate):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.__itemList=[]
        self.__isEditable=False
    def setItems(self,itemList,isEditable=False):
        self.__itemList=itemList
        self.__isEditable=isEditable

    def createEditor(self, parent, option, index):
        editor=QComboBox(parent)
        editor.setFrame(False)
        editor.setEditable(self.__isEditable)
        editor.addItems(self.__itemList)
        return editor
    def setEditorData(self, editor, index):
        model=index.model()
        text=model.data(index,Qt.EditRole)
        editor.setCurrentText(text)
    def setModelData(self, editor, model, index):
        text=editor.currentText()
        model.setData(index,text,Qt.EditRole)
    def updateEditorGeometry(self, editor, option, index):
        editor.setGeometry(option.rect)
    
import sys,os
from PyQt5.QtWidgets import (QApplication,QMainWindow,QLabel,QAbstractItemView,QFileDialog)
from PyQt5.QtCore import Qt,pyqtSlot,QItemSelectionModel,QDir,QModelIndex
from PyQt5.QtGui import QStandardItemModel,QStandardItem
from PyQt5 import QtCore
from ui_Mainwindow import Ui_MainWindow
from myDelegates import QmyFloatSpinDelegate,QmyComboBoxDelegate

class QmyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)

        self.__ColCount=6
        self.itemModel=QStandardItemModel(5,self.__ColCount,self)
        self.selectionModel=QItemSelectionModel(self.itemModel)
        self.selectionModel.currentChanged.connect(self.do_curChanged)
        self.__lastColumnTitle="测井取样"#最后一列文字
        self.__lastColumnFlags=(Qt.ItemIsSelectable|Qt.ItemIsUserCheckable|Qt.ItemIsEnabled)
        self.ui.tableView.setModel(self.itemModel)#数据模型
        self.ui.tableView.setSelectionModel(self.selectionModel)#选择模型
        oneOrMore=QAbstractItemView.ExtendedSelection
        self.ui.tableView.setSelectionMode(oneOrMore)
        itemOrRow=QAbstractItemView.SelectItems#项选择模式
        self.ui.tableView.setSelectionBehavior(itemOrRow)
        self.ui.tableView.verticalHeader().setDefaultSectionSize(22)
        self.ui.tableView.setAlternatingRowColors(True)#交替行颜色
        self.ui.tableView.setEnabled(False)#先禁用tableview
        # self.setCentralWidget(self.ui.splitter)
        self.__buildStatusBar()

        #创建自定义代理组件并设置
        self.spinCeShen=QmyFloatSpinDelegate(0,10000,0,self)#用于探测
        self.spinLength=QmyFloatSpinDelegate(0,6000,2,self)#垂深,总位移
        self.spinDegree=QmyFloatSpinDelegate(0,360,1,self)#方位
        self.ui.tableView.setItemDelegateForColumn(0,self.spinCeShen)
        self.ui.tableView.setItemDelegateForColumn(1,self.spinLength)
        self.ui.tableView.setItemDelegateForColumn(3,self.spinLength)
        self.ui.tableView.setItemDelegateForColumn(2,self.spinDegree)

        qualities=["优","良","合格","不合格"]
        self.comboDelegete=QmyComboBoxDelegate(self)
        self.comboDelegete.setItems(qualities,False)
        self.ui.tableView.setItemDelegateForColumn(4,self.comboDelegete)
    
    def __buildStatusBar(self):#构建状态栏
        self.LabCellPos=QLabel("当前单元格:",self)
        self.LabCellPos.setMinimumWidth(180)
        self.ui.statusbar.addWidget(self.LabCellPos)

        self.LabCellText=QLabel("单元格内容:",self)
        self.LabCellText.setMinimumWidth(150)
        self.ui.statusbar.addWidget(self.LabCellText)

        self.LabCurFile=QLabel("当前文件:",self)
        self.ui.statusbar.addPermanentWidget(self.LabCurFile)
    
    def do_curChanged(self,current,previous):
        if(current!=None):
            text="当前单元格:%d行,%d列"%(current.row(),current.column())
            self.LabCellPos.setText(text)
            item=self.itemModel.itemFromIndex(current)#从当前模型索引获得item
            self.LabCellText.setText("单元格内容:"+item.text())
            font=item.font()
            self.ui.actFontBold.setChecked(font.bold())
    
    @pyqtSlot()
    def on_actOpen_triggered(self):
        curPath=os.getcwd()#获取当前路径
        filename,flt=QFileDialog.getOpenFileName(self,"打开一个文件",curPath,"井斜数据文件(*.txt);所有文件(*.*)")
        if(filename==''):
            return 
        self.LabCurFile.setText("当前文件:"+filename)
        self.ui.plainTextEdit.clear()
        aFile=open(filename,'r')
        allLines=aFile.readlines()#读取所有行,list类型,每行末尾带有\n
        aFile.close()
        for strLine in allLines:
            self.ui.plainTextEdit.appendPlainText(strLine.strip())
        self.__iniModelFromStringList(allLines)
        self.ui.tableView.setEnabled(True)
        self.ui.actAppend.setEnabled(True)
        self.ui.actInsert.setEnabled(True)
        self.ui.actSave.setEnabled(True)
        self.ui.actModelData.setEnabled(True)
    def __iniModelFromStringList(self,allLines):
        rowCnt=len(allLines)#文本行数,第一行是标题
        self.itemModel.setRowCount(rowCnt-1)
        headerText=allLines[0].strip()#第一行是表头,去掉末尾的换行符
        headerList=headerText.split("\t")
        self.itemModel.setHorizontalHeaderLabels(headerList)#设置表头标题
        self.__lastColumnTitle=headerList[len(headerList)-1]#最后一列标题

        lastColNo=self.__ColCount-1
        for i in range(rowCnt-1):
            lineText=allLines[i+1].strip()
            strList=lineText.split("\t")
            for j in range(self.__ColCount-1):
                item=QStandardItem(strList[j])
                self.itemModel.setItem(i,j,item)
            item=QStandardItem(self.__lastColumnTitle)
            item.setFlags(self.__lastColumnFlags)
            item.setCheckable(True)
            if(strList[lastColNo]=='0'):
                item.setCheckState(Qt.Unchecked)
            else:
                item.setCheckState(Qt.Checked)
            self.itemModel.setItem(i,lastColNo,item)
    @pyqtSlot()
    def on_actAppend_triggered(self):
        itemlist=[]
        for i in range(self.__ColCount-1):
            item=QStandardItem("0")
            itemlist.append(item)
        item=QStandardItem(self.__lastColumnTitle)#最后一列
        item.setCheckable(True)
        item.setFlags(self.__lastColumnFlags)
        itemlist.append(item)
        self.itemModel.appendRow(itemlist)
        curIndex=self.itemModel.index(self.itemModel.rowCount()-1,0)
        self.selectionModel.clearSelection()
        self.selectionModel.setCurrentIndex(curIndex,QItemSelectionModel.Select)#选择单元格
    @pyqtSlot()
    def on_actInsert_triggered(self):
        itemlist=[]
        for i in range(self.__ColCount-1):
            item=QStandardItem("0")
            itemlist.append(item)
        item=QStandardItem(self.__lastColumnTitle)
        item.setFlags(self.__lastColumnFlags)
        item.setCheckable(True)
        item.setCheckState(Qt.Checked)
        itemlist.append(item)

        curIndex=self.selectionModel.currentIndex()
        self.itemModel.insertRow(curIndex.row(),itemlist)
        self.selectionModel.clearSelection()
        self.selectionModel.setCurrentIndex(curIndex,QItemSelectionModel.Select)
    @pyqtSlot()
    def on_actDel_triggered(self):
        curIndex=self.selectionModel.currentIndex()
        self.itemModel.removeRow(curIndex.row())#删除当前行
    @pyqtSlot()
    def on_actAlignLeft_triggered(self):
        self.__setCellAlignment(Qt.AlignLeft|Qt.AlignVCenter)
    @pyqtSlot()
    def on_actAlignCenter_triggered(self):
        self.__setCellAlignment(Qt.AlignHCenter|Qt.AlignVCenter)
    @pyqtSlot()
    def on_actAlignRight_triggered(self):
        self.__setCellAlignment(Qt.AlignRight|Qt.AlignVCenter) 
    def __setCellAlignment(self,align=Qt.AlignHCenter):
        if(not self.selectionModel.hasSelection()):
            return
        selectedIndex=self.selectionModel.selectedIndexes()#模型索引列表
        count=len(selectedIndex)
        for i in range(count):
            index=selectedIndex[i]
            item=self.itemModel.itemFromIndex(index)#获取一个单元格的item
            item.setTextAlignment(align)
    @pyqtSlot(bool)
    def on_actFontBold_triggered(self,checked):
        if (not self.selectionModel.hasSelection()):
            return 
        # print("yes")
        selectedIndex=self.selectionModel.selectedIndexes()#模型索引列表
        count=len(selectedIndex)
        for i in range(count):
            index=selectedIndex[i]#获取其中一个模型索引
            item=self.itemModel.itemFromIndex(index)#获取单元格的item
            font=item.font()
            font.setBold(checked)
            item.setFont(font)
    @pyqtSlot()#模型数据显示到plainTextEdit
    def on_actModelData_triggered(self):
        self.ui.plainTextEdit.clear()
        lineStr=""
        for i in range(self.itemModel.columnCount()-1):
            item=self.itemModel.horizontalHeaderItem(i)
            lineStr=lineStr+item.text()+'\t'
        item=self.itemModel.horizontalHeaderItem(self.__ColCount-1)#最后一列
        lineStr=lineStr+item.text()
        self.ui.plainTextEdit.appendPlainText(lineStr)
        for i in range(self.itemModel.rowCount()):
            lineStr=""
            for j in range(self.itemModel.columnCount()-1):
                item=self.itemModel.item(i,j)
                lineStr=lineStr+item.text()+'\t'
            item=self.itemModel.item(i,self.__ColCount-1)#最后一列
            if(item.checkState()==Qt.Checked):
                lineStr=lineStr+'1'
            else:
                lineStr=lineStr+'0'
            self.ui.plainTextEdit.appendPlainText(lineStr)
    @pyqtSlot()#保存文件
    def on_actSave_triggered(self):
        curPath=os.getcwd()
        filename,flt=QFileDialog.getSaveFileName(self,"保存文件",curPath,"*.txt")
        if(filename==''):
            return 
        self.on_actModelData_triggered()#更新到plain
        aFile=open(filename,'w')
        aFile.write(self.ui.plainTextEdit.toPlainText())
        aFile.close()
if __name__=="__main__":
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)#自适应缩放
    app=QApplication(sys.argv)
    form=QmyMainWindow()
    form.show()
    sys.exit(app.exec_())
    

自定义代理_第1张图片

 

你可能感兴趣的:(Pyqt5)