简体   繁体   中英

How can I style the cells of a QTableWidget in PyQt5?

I'm new to Qt and PyQt and wonder how to style the cells of a QTableWidget. For example, I want to add some etxra padding. I tried to set a stylesheet like in the code below, but it doesn't have any effect. I also searched the internet, but couldn't find a solution.

I use PyQT5 (python-pyqt5 5.15.4-1 on Arch Linux).

This is my code:

import sys

from PyQt5.QtWidgets import QApplication,QMainWindow, QTableWidget, QTableWidgetItem


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Table Test')
        table = QTableWidget(self)
        table.setColumnCount(4)
        table.setRowCount(3)
        for j in range(table.rowCount()):
            for k in range(table.columnCount()):
                table.setItem(j, k, QTableWidgetItem("{}{}".format(j, k)))
        self._centralWidget = table
        self.setCentralWidget(self._centralWidget)
        self.resize(500, 200)


def main():
    app = QApplication(sys.argv)
    view = MainWindow()
    view.setStyleSheet("QTableWidget::item {padding: 5px}")
    view.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

Can anybody please help?

I answer the question myself. I found the solution with the help of the comment of @musicamante above.

Setting the margin to 0 did the trick:

view.setStyleSheet("QTableWidget::item {border: 0px; padding: 5px;}")

Now the cells have a padding of 5px.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM