1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import Qt, QAbstractTableModel, QVariant, QSortFilterProxyModel
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QTableView, QAbstractItemView, QPushButton
from operator import attrgetter
class obj(object):
def __init__(self, col0, park):
self.col0, self.park= col0, park
class ContentModel(QAbstractTableModel):
def __init__(self, data, header, parent):
QAbstractTableModel.__init__(self, parent)
self.data, self.header= data, header
def rowCount(self, content= None):
return len(self.data)
def columnCount(self, content):
return len(self.header)
def data(self, index, role):
return getattr(self.data[index.row()], "col" + str(index.column())) if index.isValid() and role == Qt.DisplayRole else None
def headerData(self, col, orientation, role):
return QVariant(self.header[col]) if orientation == Qt.Horizontal and role == Qt.DisplayRole else None
def sort(self, col, order):
self.layoutAboutToBeChanged.emit()
self.data.sort(key= attrgetter("col" + str(col)), reverse= True if order == Qt.DescendingOrder else False)
self.layoutChanged.emit()
class Content(QWidget):
def __init__(self):
QWidget.__init__(self)
self.layout, self.tableView, self.proxy, self.table= QVBoxLayout(), QTableView(), QSortFilterProxyModel(), list()
self.table.append(obj("Clio (1)", 1))
self.table.append(obj("Megane (10)", 10))
self.table.append(obj("Twingo (100)", 100))
self.proxy.setSourceModel(ContentModel(self.table, ["Modèle"], self))
self.tableView.setModel(self.proxy)
self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
self.tableView.setSortingEnabled(True)
self.tableView.sortByColumn(0, Qt.AscendingOrder)
self.tableView.verticalHeader().setVisible(False)
self.layout.addWidget(self.tableView)
self.layout.addWidget(QPushButton("Libère", self, clicked= self.delete))
self.setLayout(self.layout)
def delete(self):
for index in self.tableView.selectionModel().selectedRows():
print(index.data(), "=", self.table[index.row()].park)
if __name__ == "__main__":
app, ui= QApplication([]), Content()
ui.show()
exit(app.exec_()) |
Partager