Skip to content

Instantly share code, notes, and snippets.

@eyllanesc
Created January 4, 2018 22:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eyllanesc/79a6f3e85912b6a954edcdf7f291469a to your computer and use it in GitHub Desktop.
Save eyllanesc/79a6f3e85912b6a954edcdf7f291469a to your computer and use it in GitHub Desktop.
from PySide2.QtWidgets import *
from PySide2.QtCore import *
class Model(QAbstractTableModel):
def __init__(self, cycles = [[]], headers = [], parent = None):
QAbstractTableModel.__init__(self, parent)
self.cycles = cycles
self.headers = headers
self.values_checked = []
self.column_count = len(self.cycles[0])
def rowCount(self, parent=QModelIndex()):
return len(self.cycles)
def columnCount(self, parent=QModelIndex()):
return self.column_count
def flags(self, index):
fl = Qt.ItemIsEnabled | Qt.ItemIsSelectable
if index.column() == 0:
fl |= Qt.ItemIsUserCheckable
else:
fl |= Qt.ItemIsEditable
return fl
def data(self, index, role):
if not index.isValid():
return
row = index.row()
column = index.column()
if role == Qt.DisplayRole:
value = self.cycles[row][column]
return value
elif role == Qt.TextAlignmentRole:
return Qt.AlignCenter;
elif role == Qt.CheckStateRole and column==0:
return Qt.Checked if self.cycles[row][column] else Qt.Unchecked
def setData(self, index, value, role = Qt.EditRole):
change = False
row = index.row()
column = index.column()
if role == Qt.CheckStateRole:
value = value != Qt.Unchecked
change = True
if role == Qt.EditRole:
if (column == 1) or (column == 4):
try:
str(value)
change = True
except:
pm.warning("Not a valid name")
change = False
elif (column == 2):
try:
int(value)
change = True
except:
pm.warning("Not a valid frame")
change = False
elif (column == 3):
try:
int(value)
change = True
except:
pm.warning("Not a valid frame")
change = False
elif (column == 5):
try:
int(value)
change = True
except:
pm.warning("Not a valid version number")
change = False
if change:
self.cycles[row][column] = value
self.dataChanged.emit(row, column)
return True
return False
def headerData(self, section, orientation, role):
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
return self.headers[section]
def insertRows(self, position, rows, values = [] , parent =QModelIndex()):
self.beginInsertRows(parent, position, position+rows-1)
self.cycles.insert(position, values)
self.endInsertRows()
self.getData()
def roleNames(self):
roles = QAbstractTableModel.roleNames(self)
roles["Checked"] = Qt.CheckStateRole
return roles
def removeRow(self, row, parent=QModelIndex()):
self.beginRemoveRows(parent, row, row)
self.cycles.remove(self.cycles[row])
self.endRemoveRows()
self.getData()
def getData(self):
rows = self.rowCount(1)
data = []
for row in range(rows):
array = []
for column in range (6):
index = self.index(row, column)
info = index.data()
array.append(info)
data.append(array)
dic = {}
for item in data:
dic[item[1]]=item
print("")
print("data:")
print('')
for key in dic:
print(key, dic[key])
class EmptyDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
opt = QStyleOptionViewItem(option)
self.initStyleOption(opt, index)
opt.text = ""
QApplication.style().drawControl(QStyle.CE_ItemViewItem, opt, painter)
class ButtonDelegate(QItemDelegate):
def __init__(self, parent):
QItemDelegate.__init__(self, parent)
def paint(self, painter, option, index):
widget = QWidget()
layout = QHBoxLayout()
widget.setLayout(layout)
btn = QPushButton("X")
ix = QPersistentModelIndex(index)
btn.clicked.connect(lambda ix = ix : self.onClicked(ix))
layout.addWidget(btn)
layout.setContentsMargins(2,2,2,2)
if not self.parent().indexWidget(index):
self.parent().setIndexWidget(index, widget)
def onClicked(self, ix):
model = ix.model()
model.removeRow(ix.row())
self.parent().clearSelection()
class Table(QTableView):
def __init__(self, *args, **kwargs):
QTableView.__init__(self, *args, **kwargs)
self.setItemDelegateForColumn(6, ButtonDelegate(self))
self.setItemDelegateForColumn(0, EmptyDelegate(self))
self.setSortingEnabled(True)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = Table()
headers = ["Select", " Cycle Name ", " Start ", " End ", "Info", "Version", " Del "]
cycles = [[True,"idle","1","70","cool information","0", "deleteBtnPlaceHolder"]]*10
model = Model(cycles, headers)
w.setModel(model)
w.show()
sys.exit(app.exec_())
from PySide2.QtWidgets import *
from PySide2.QtCore import *
class Model(QAbstractTableModel):
def __init__(self, cycles = [[]], headers = [], parent = None):
QAbstractTableModel.__init__(self, parent)
self.cycles = cycles
self.headers = headers
self.values_checked = []
self.column_count = len(self.cycles[0])
def rowCount(self, parent=QModelIndex()):
return len(self.cycles)
def columnCount(self, parent=QModelIndex()):
return self.column_count
def flags(self, index):
fl = Qt.ItemIsEnabled | Qt.ItemIsSelectable
if index.column() == 0:
fl |= Qt.ItemIsUserCheckable
else:
fl |= Qt.ItemIsEditable
return fl
def data(self, index, role):
if not index.isValid():
return
row = index.row()
column = index.column()
if role == Qt.DisplayRole:
value = self.cycles[row][column]
return value
elif role == Qt.TextAlignmentRole:
return Qt.AlignCenter;
elif role == Qt.CheckStateRole and column==0:
return Qt.Checked if self.cycles[row][column] else Qt.Unchecked
def setData(self, index, value, role = Qt.EditRole):
change = False
row = index.row()
column = index.column()
if role == Qt.CheckStateRole:
value = value != Qt.Unchecked
change = True
if role == Qt.EditRole:
if (column == 1) or (column == 4):
try:
str(value)
change = True
except:
pm.warning("Not a valid name")
change = False
elif (column == 2):
try:
int(value)
change = True
except:
pm.warning("Not a valid frame")
change = False
elif (column == 3):
try:
int(value)
change = True
except:
pm.warning("Not a valid frame")
change = False
elif (column == 5):
try:
int(value)
change = True
except:
pm.warning("Not a valid version number")
change = False
if change:
self.cycles[row][column] = value
self.dataChanged.emit(row, column)
return True
return False
def headerData(self, section, orientation, role):
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
return self.headers[section]
def insertRows(self, position, rows, values = [] , parent =QModelIndex()):
self.beginInsertRows(parent, position, position+rows-1)
self.cycles.insert(position, values)
self.endInsertRows()
self.getData()
def roleNames(self):
roles = QAbstractTableModel.roleNames(self)
roles["Checked"] = Qt.CheckStateRole
return roles
def removeRow(self, row, parent=QModelIndex()):
self.beginRemoveRows(parent, row, row)
self.cycles.remove(self.cycles[row])
self.endRemoveRows()
self.getData()
def getData(self):
rows = self.rowCount(1)
data = []
for row in range(rows):
array = []
for column in range (6):
index = self.index(row, column)
info = index.data()
array.append(info)
data.append(array)
dic = {}
for item in data:
dic[item[1]]=item
print("")
print("data:")
print('')
for key in dic:
print(key, dic[key])
class EmptyDelegate(QStyledItemDelegate):
def paint(self, painter, option, index):
opt = QStyleOptionViewItem(option)
self.initStyleOption(opt, index)
opt.text = ""
QApplication.style().drawControl(QStyle.CE_ItemViewItem, opt, painter)
class ButtonDelegate(QStyledItemDelegate):
def __init__(self, parent):
QStyledItemDelegate.__init__(self, parent)
self.state = QStyle.State_Enabled
def paint(self, painter, option, index):
button = QStyleOptionButton()
button.rect = self.adjustRect(option.rect)
button.text = "X"
button.state = self.state
QApplication.style().drawControl(QStyle.CE_PushButton, button, painter)
def editorEvent(self, event, model, option, index):
if event.type() == QEvent.Type.MouseButtonPress:
self.state = QStyle.State_On
return True
elif event.type() == QEvent.Type.MouseButtonRelease:
r = self.adjustRect(option.rect)
if r.contains(event.pos()):
model.removeRow(index.row())
self.state = QStyle.State_Enabled
return True
@staticmethod
def adjustRect(rect):
r = QRect(rect)
margin = QPoint(2, 2)
r.translate(margin)
r.setSize(r.size()-2*QSize(margin.x(), margin.y()))
return r
class Table(QTableView):
def __init__(self, *args, **kwargs):
QTableView.__init__(self, *args, **kwargs)
self.setItemDelegateForColumn(6, ButtonDelegate(self))
self.setItemDelegateForColumn(0, EmptyDelegate(self))
self.setSortingEnabled(True)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = Table()
headers = ["Select", " Cycle Name ", " Start ", " End ", "Info", "Version", " Del "]
cycles = [[True,"idle","1","70","cool information","0", "deleteBtnPlaceHolder"]]*10
model = Model(cycles, headers)
w.setModel(model)
w.show()
sys.exit(app.exec_())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment