PyQt4-PySide - 格式化表格小部件

时间:2013-03-19 14:35:53

标签: python pyqt pyqt4 pyside styling

在下面的代码中,我想在第2列和第3列之间使用更粗的规则分隔符。我怎样才能做到这一点?

#! /usr/bin/env python2.7
# -*- coding: utf-8 -*-

import sys

from PySide import QtCore, QtGui

class MainWindow(QtGui.QWidget):
    def __init__(
        self,
        parent = None
    ):
        super(MainWindow, self).__init__(parent)

# General grid
        self.table = QtGui.QTableWidget(self)
        self.nbrow, self.nbcol = 9, 9
        self.table.setRowCount(self.nbrow)
        self.table.setColumnCount(self.nbcol)

# Each cell has dimension 50 pixels x 50 pixels
        for row in range(0, self.nbrow):
            self.table.setRowHeight(row, 50)

            for col in range(0, self.nbcol):
                self.table.setColumnWidth(col, 50)

# Each cell contains one single QTableWidgetItem
        for row in range(0, self.nbrow):
            for col in range(0, self.nbcol):
                item = QtGui.QTableWidgetItem()
                item.setTextAlignment(
                    QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter
                )

                self.table.setItem(row, col, item)

# Header formatting
        font = QtGui.QFont()
        font.setFamily(u"DejaVu Sans")
        font.setPointSize(12)
        self.table.horizontalHeader().setFont(font)
        self.table.verticalHeader().setFont(font)

# Font used
        font = QtGui.QFont()
        font.setFamily(u"DejaVu Sans")
        font.setPointSize(20)
        self.table.setFont(font)

# Global Size
        self.resize(60*9, 60*9 + 20)

# Layout of the table
        layout = QtGui.QGridLayout()
        layout.addWidget(self.table, 0, 0)
        self.setLayout(layout)

# Set the focus in the first cell
        self.table.setFocus()
        self.table.setCurrentCell(0, 0)


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    fen = MainWindow()
    fen.show()
    sys.exit(app.exec_())

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

这不是一个完整或理想的解决方案,但它有些相关,可能有助于取得进展。我找到了一个在Qt中更改整个单元格边框的示例,并将其转换为PyQt。

首先,创建一个委托并覆盖其绘制方法以进行所需的自定义。

class TableBorderDelegate(QtGui.QItemDelegate):
    """Delegate for customizing cell borders"""

    def paint(self, painter, option, index):
        """Overrides paint to put a red border around cells in column 3"""
        if index.column() == 3:  # index.row() is also a thing
            painter.setPen(QtGui.QColor(255, 0, 0))
            painter.drawRect(option.rect)
        QtGui.QItemDelegate.paint(self, painter, option, index)
    # End of class TableBorderDelegate

然后在您的表格中

delegate = TableBorderDelegate()
self.table.setItemDelegate(delegate) 

self.tableQtGui.QTableWidget()的实例

Qt解决方案来自https://stackoverflow.com/a/7264248/6605826。 我在https://github.com/baoboa/pyqt5/blob/master/examples/itemviews/spinboxdelegate.py中找到了不相关的pyqt委托的pyqt示例