QTableView中的单元格间距和焦点矩形

时间:2014-07-24 16:57:26

标签: qt pyside

我有一个QTableView,它显示了我自定义的QAbstractTableModel子类中的一些数据。问题是文本被推向单元格的左侧。我发现了这个问题:How to set the padding of QTableView cells through CSS?它让我尝试了这个:

self.tableView.setStyleSheet('QTableView::item {border: 0px; padding: 5px;} ')

缩进文本但引入了一个新问题。现在,当我单击一个单元格时,点状的焦点矩形将嵌入单元格中。

如何同时包含单元格间距和围绕整个单元格的虚线焦点矩形(不插入)?

2 个答案:

答案 0 :(得分:2)

使用CSS并不是最好的方法,花5分钟的时间写代表,这很容易。 但你可以尝试:

QTableView {
   outline: 0; /* Disable focus rect*/
}  
QTableView:item {
  border: 0px;
  padding: 0px 10px;
}
QTableView::item:focus { /*Emulate focus*/
    color: black;
    background-color: yellow;
    border: 1px dashed black;
}

答案 1 :(得分:0)

这是我最终能够想到的。它将焦点矩形放在每个单元格的边框上,而不管" padding"或"保证金"。它还保留样式表。至少它保留了背景颜色和填充。我没有测试所有样式表选项。但是,它不会保留具有焦点的单元格中的文本颜色。 (P.S.这与PySide 1.1.1合作)

class CellDelegate(QtGui.QStyledItemDelegate):
    def __init__(self, parent):
        super(CellDelegate, self).__init__(parent)
        self._parent = parent

    def paint(self, qPainter, option, qModelIndex):
        v4Option = QtGui.QStyleOptionViewItemV4(option)
        v4Option.index = qModelIndex
        value = qModelIndex.data()
        v4Option.text = str(value)

        style = self._parent.style()

        if (v4Option.state & QtGui.QStyle.State_HasFocus):
            # --- The table cell with focus
            # Draw the background
            style.drawPrimitive(style.PE_PanelItemViewItem, v4Option, qPainter, self._parent)

            # Draw the text
            subRect = style.subElementRect(style.SE_ItemViewItemText, v4Option, self._parent)
            alignment = qModelIndex.data(QtCore.Qt.TextAlignmentRole)
            if not alignment:
                alignment = int(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
            if (v4Option.state & QtGui.QStyle.State_Enabled):
                itemEnabled = True
            else:
                itemEnabled = False
            textRect = style.itemTextRect(v4Option.fontMetrics, subRect, alignment, itemEnabled, value)
            style.drawItemText(qPainter, textRect, alignment, v4Option.palette, v4Option.state, value)

            # Draw the focus rectangle
            focusOption = QtGui.QStyleOptionFocusRect()
            focusOption.rect = v4Option.rect
            style.drawPrimitive(style.PE_FrameFocusRect, focusOption, qPainter, self._parent)
        else:
            # --- All other table cells
            style.drawControl(style.CE_ItemViewItem, v4Option, qPainter, self._parent)

以下是一些示例代码,展示了如何使用它。目标是样式表将设置在.ui文件中。这只是一个独立的例子:

class TestTableModel(QtCore.QAbstractTableModel):
    headerNames = ('Column 1', 'Column 2')
    def __init__(self):
        super(TestTableModel, self).__init__()
        self._data = [['test', 'text'], ['yyy', 'zzz']]

    #----- Overridden Functions ------------------------------------------------
    def columnCount(self, parentIndex):
        return len(self.headerNames)

    def data(self, qModelIndex, role=QtCore.Qt.DisplayRole):
        if qModelIndex.isValid():
            if role in (QtCore.Qt.DisplayRole, QtCore.Qt.EditRole):
                dataItem = self._data[qModelIndex.row()][qModelIndex.column()]
                return dataItem
        return None

    def headerData(self, colNum, orientation, role):
        if (orientation == QtCore.Qt.Horizontal) and (role == QtCore.Qt.DisplayRole):
            return self.headerNames[colNum]
        return None

    def rowCount(self, parentIndex=QtCore.QModelIndex()):
        return len(self._data)

#------------------------------------------------------------------------------
class TestTableViewSpacing(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(TestTableViewSpacing, self).__init__(parent)

        self.tableView = QtGui.QTableView()
        self.setCentralWidget(self.tableView)

        tableModel = TestTableModel()
        self.tableView.setModel(tableModel)

        self.tableView.setStyleSheet('QTableView::item {border: 0px; padding: 5px; margin: 5px; color: yellow; '
                                     'background-color: QLinearGradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #330055, stop: 1 #000000);} '
                                     'QTableView::item:focus {border: 0px; background-color: darkred; color: yellow;}')

        # VERY IMPORTANT!! Must pass the table view to the delegate, or it will not work!
        newDelegate = CellDelegate(self.tableView)
        self.tableView.setItemDelegate(newDelegate)