提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
示例代码
# -*- coding:utf-8 -*-
import sys
from PySide6.QtCore import *
from PySide6.QtGui import *
from PySide6.QtWidgets import *
class DelegateButton( QStyledItemDelegate ) :
onClick = Signal( int, int )
def __init__( self, parent=None ) :
super().__init__(parent)
self._mybtn = None
self._pressed = None
self._rfbutton = QPushButton()
# 关闭编辑功能
# 可以通过返回QWidget实现自定义的编辑器,同时可能需要实现以下方法:
# setEditorData( self, editor, index )
# setModelData( self, editor, model, index )
# updateEditorGeometry(self, editor, option, index )
def createEditor( self, parent, option, index ) :
return None
# 自定义绘制
def paint( self, painter, option, index ) :
self._mybtn = self._mybtn or QStyleOptionButton()
if index.row() % 2 == 0 :
# 修改偶数行的按钮大小
top_span_height = (option.rect.height() - 24)/2
pos_x = 8 + option.rect.x()
pos_y = option.rect.y() + top_span_height
self._mybtn.rect = QRect(pos_x, pos_y, 24, 24)
self._mybtn.text = str(index.row())
else :
# 让奇数行的按钮占满整个option(单元格)对应的区域
self._mybtn.rect = option.rect
data= index.model().data(index)
self._mybtn.text = str(data)
# 如果点击的位置在self._myBtn的区域,修改按钮状态
if self._pressed and self._mybtn.rect.contains(self._pressed) :
# 触发信号
self.onClick.emit(index.row(), index.column())
# 修改按钮状态
self._mybtn.state = QStyle.State_Enabled | QStyle.State_Sunken
else:
self._mybtn.state = QStyle.State_Enabled
# 绘制按钮
self._rfbutton.style().drawControl(QStyle.CE_PushButton, self._mybtn, painter, self._rfbutton)
# 处理鼠标事件
def editorEvent( self, event, model, option, index ) :
if event.type() == QEvent.MouseButtonPress :
# 如果点击的位置在option的区域,记录点击的位置
pos = event.position()
if option.rect.contains(pos.x(), pos.y()) :
self._pressed = QPoint(pos.x(), pos.y())
return True
if event.type() == QEvent.MouseButtonRelease :
# 鼠标点击完成后重置点击位置为None
self._pressed = None
return True
return False
if __name__ == '__main__' :
app = QApplication(sys.argv)
rows = 5
cols = 2
model = QStandardItemModel(rows, cols)
tableView = QTableView()
tableView.setWindowTitle("Delegate Issue")
tableView.setModel(model)
delegate = DelegateButton()
delegate.onClick.connect(lambda a, b : print('onClick, row:%d, column:%d'%(a, b)))
tableView.setItemDelegateForColumn(1, delegate)
tableView.setColumnWidth(0, 200)
tableView.setColumnWidth(1, 200)
tableView.verticalHeader().setDefaultSectionSize(32)
tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
for row in range(rows) :
index = model.index(row, 0)
model.setData(index, row if row % 2 == 0 else 'info: %d'%row)
index = model.index(row, 1)
model.setData(index, {'data': row})
tableView.show()
tableView.resize(450,300)
sys.exit(app.exec())
效果图
参考链接
QStyledItemDelegate
PySide: QStyledItemDelegate button’s stylesheet Issue