需求:鼠標左鍵點擊表格后,對應的單元格背景顏色發生變化。
實現:(1)使用Qt的model-view模式生成表格視圖。
(2)重寫表格的點擊事件。
(3)設置表格的背景顏色。
正常情況下,當用戶選中單元格之后單元格背景顏色變為藍色,如下圖所示:
如果覺得這樣表格過於單調,那么我們就用鼠標為它塗上顏色。
代碼塊:
View部分。
class MyTableView(QTableView): """View""" SelectedCellSignal = pyqtSignal(QModelIndex) def __init__(self): super(MyTableView, self).__init__() def mousePressEvent(self, e): """重寫鼠標點擊事件。""" if e.button() == Qt.RightButton: return super().mousePressEvent(e) # :獲取鼠標點擊的索引 index = self.indexAt(e.pos()) return self.SelectedCellSignal.emit(index)
Model部分。
class MyTableModel(QAbstractTableModel): """Model""" def __init__(self): super(MyTableModel, self).__init__() self._data = [] self._background_color = [] self._headers = ['序號', '姓名', '性別', '年齡'] self._generate_data() def _generate_data(self): """填充表格數據""" name_list = ['張三', '李四', '王五', '王小二', '李美麗', '王二狗'] for id_num, name in enumerate(name_list): self._data.append([str(id_num), name, '男', str(random.randint(20, 25))]) # :默認單元格顏色為白色 self._background_color.append([QColor(255, 255, 255) for i in range(4)]) def rowCount(self, parent=QModelIndex()): """返回行數量。""" return len(self._data) def columnCount(self, parent=QModelIndex()): """返回列數量。""" return len(self._headers) def headerData(self, section, orientation, role): """設置表格頭""" if role == Qt.DisplayRole and orientation == Qt.Horizontal: return self._headers[section] def data(self, index, role): """顯示表格中的數據。""" if not index.isValid() or not 0 <= index.row() < self.rowCount(): return QVariant() row = index.row() col = index.column() if role == Qt.DisplayRole: return self._data[row][col] elif role == Qt.BackgroundColorRole: return self._background_color[row][col] elif role == Qt.TextAlignmentRole: return Qt.AlignCenter return QVariant() def cellPaint(self, index, color): """給單元格填充顏色。""" row = index.row() col = index.column() self._background_color[row][col] = QColor(color) self.layoutChanged.emit()
窗體繪制:
class ColorfulTable(QWidget): def __init__(self): super().__init__() self.setWindowTitle('變色的表格') self.tableView = MyTableView() self.tableModel = MyTableModel() self.tableView.setModel(self.tableModel) self.tableView.SelectedCellSignal.connect(self.selectedCell) layout = QHBoxLayout() layout.addWidget(self.tableView) self.setLayout(layout) def selectedCell(self, index): """鼠標點擊事件槽函數。""" # :生成顏色字符串形如:#FFFFFF color = '#{}'.format(''.join([hex(random.randint(0, 256))[2:].rjust(2, '0') for i in range(3)])) self.tableModel.cellPaint(index, color)