QSqltablemodel + tableview 用委托 显示图片 PyQt5

完整项目:https://github.com/625781186/CodeTip

先前用自定义model继承了QSqltablemodel ,但是效果不好,很多继承的函数会莫名奇妙的失效,所以用委托来写一个。

官方案例:C:\Users\XXXAppData\Local\Programs\Python\Python35\Lib\site-packages\PyQt5\examples\itemviews

下的 spinboxdelegate.py 和 stardelegate.py。

效果图:

    

 1. 先创建model     

self.codeModel = QSqlTableModel()
self.codeModel.setEditStrategy(QSqlTableModel.OnFieldChange)

 2.创建视图

self.codeView =  QTableView()
self.codeView.setModel(self.codeModel)
self.delegate=SpinBoxDelegate() #委托
self.codeView.setItemDelegate(self.delegate)

3.委托代码

#!/usr/bin/env python




from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *


import time


class SpinBoxDelegate(QItemDelegate, ):
    def __init__(self,  parent=None, *args):
        super(SpinBoxDelegate, self).__init__(parent, *args)
        self.timer=QTimer()


    def paint(self, painter, option, index):
        item=self.getPixmat(index, option)
        pixmap = item['pixmap']
#            print(option.rect, type(option.rect))
#        painter.fillRect(option.rect, option.palette.highlight())
        if item['bool']==False:
            super(SpinBoxDelegate, self).paint(painter, option, index)           
        
        else:
            painter.drawPixmap( option.rect.x() ,
                                option.rect.y() , 
                                item['width'] , 
                                item['height'] , 
                                pixmap )
    def sizeHint(self, option, index):
        item=self.getPixmat(index, option)
        if item['bool']==True:
            width=item['width']
            height=item['height']
            return QSize(width,height)
        else:
            return super(SpinBoxDelegate, self).sizeHint(option, index)


    def createEditor(self, parent, option, index):


        editor = QLineEdit(parent)
        return editor


    def setEditorData(self, lineEdit, index):
        value = index.model().data(index, Qt.EditRole)
        lineEdit.setText(str(value))


    def setModelData(self, lineEdit, model, index):
        value = lineEdit.text()
        model.setData(index, value, Qt.EditRole)


    def updateEditorGeometry(self, editor, option, index):
        editor.setGeometry(option.rect)
    
    def getPixmat(self,  index, option):
        '''如果index中有.jpg或.png,把路径转换为pixmap。<br>
        如果图片宽 > 格 且高 < 150 , 设置宽300,高为原高;<br>
        如果图片宽 <150 且高 > 150 , 设置宽为原宽,高为150;<br>
        如果图片宽 <150 且高 < 150 , 设置宽为原宽,高为原高;<br>
        '''
        editor = str(index.data())
        pixmap=QPixmap()
        if 'jpg' in editor.split('.') or 'png' in editor.split('.'):
            pixmap.load(editor)
            if pixmap.size().width()>option.rect.width() and pixmap.size().height()<150:
                return {'pixmap':pixmap, 'bool':True, 
                    'width':300,
                    'height':pixmap.size().height()}
            elif pixmap.size().width()<150 and pixmap.size().height()>150:
                return {'pixmap':pixmap, 'bool':True, 
                    'width':pixmap.size().width(),
                    'height':150}
            elif pixmap.size().width()>150 and pixmap.size().height()>150:
                return {'pixmap':pixmap, 'bool':True, 
                    'width':150,
                    'height':150}            
            elif pixmap.size().width()<150  and pixmap.size().height()<150:
                return {'pixmap':pixmap, 'bool':True, 
                    'width':pixmap.size().width(),
                    'height':pixmap.size().height()}
            else:
                return {'pixmap':pixmap, 'bool':True, 
                    'width':pixmap.size().width(),
                    'height':pixmap.size().height()}

        else:
            return {'pixmap':'可输入文字', 'bool':False}


    def eventFilter(self, obj, event):
        '''按下Ctrl+V后,如果粘贴板是图片,命名图片保存在ima文件夹下,<br>
           把名字给粘贴板,再把图片还原到粘贴板。'''
        if event.type()==QEvent.KeyPress: 
            if  event.key()== Qt.Key_V and event.modifiers() == Qt.ControlModifier :
                
                clipboard = QApplication.clipboard()  
                data = clipboard.mimeData()
                if data.hasImage():
                    filename= 'db/ima/'+time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())+'.jpg'
                    data.imageData().save(filename,'JPG',90)
                    im = data.imageData()
                    clipboard.setText(filename)
                    self.timer.singleShot(200, lambda:clipboard.setImage(im))  
                    
        return False

欢迎大家加入QQ群 : 432987409

微信公众号 : WoHowLearn

二维码在上面动图中


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值