Search code examples
pythonpython-3.xpyqtpyqt4qtablewidget

how to increase the row height and column width of the tablewidget


I want to add images to cells but it cant show properly,can you please tell me how to increase the row height and column width of the table widget.

Here given bellow is my code:

from PyQt4 import QtGui
import sys

imagePath = "pr.png"

class ImgWidget1(QtGui.QLabel):

    def __init__(self, parent=None):
        super(ImgWidget1, self).__init__(parent)
        pic = QtGui.QPixmap(imagePath)
        self.setPixmap(pic)

class ImgWidget2(QtGui.QWidget):

    def __init__(self, parent=None):
        super(ImgWidget2, self).__init__(parent)
        self.pic = QtGui.QPixmap(imagePath)

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.drawPixmap(0, 0, self.pic)


class Widget(QtGui.QWidget):

    def __init__(self):
        super(Widget, self).__init__()
        tableWidget = QtGui.QTableWidget(10, 2, self)
        # tableWidget.horizontalHeader().setStretchLastSection(True)
        tableWidget.resizeColumnsToContents()
        # tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # tableWidget.setFixedWidth(tableWidget.columnWidth(0) + tableWidget.columnWidth(1))
        tableWidget.resize(400,600)
        tableWidget.setCellWidget(0, 1, ImgWidget1(self))
        tableWidget.setCellWidget(1, 1, ImgWidget2(self))

if __name__ == "__main__":
    app = QtGui.QApplication([])
    wnd = Widget()
    wnd.show()
    sys.exit(app.exec_())

Solution

  • When using widgets inside the QTableWidget are not really the content of the table, they are placed on top of it, so resizeColumnsToContents() makes the size of the cells very small since it does not take into account the size of those widgets, resizeColumnsToContents() takes into account the content generated by the QTableWidgetItem.

    On the other hand if you want to set the height and width of the cells you must use the headers, in the following example the default size is set using setDefaultSectionSize():

    class Widget(QtGui.QWidget):
        def __init__(self):
            super(Widget, self).__init__()
            tableWidget = QtGui.QTableWidget(10, 2)
    
            vh = tableWidget.verticalHeader()
            vh.setDefaultSectionSize(100)
            # vh.setResizeMode(QtGui.QHeaderView.Fixed)
    
            hh = tableWidget.horizontalHeader()
            hh.setDefaultSectionSize(100)
            # hh.setResizeMode(QtGui.QHeaderView.Fixed)
    
            tableWidget.setCellWidget(0, 1, ImgWidget1())
            tableWidget.setCellWidget(1, 1, ImgWidget2())
    
            lay = QtGui.QVBoxLayout(self)
            lay.addWidget(tableWidget)
    

    If you want the size can not be varied by the user then uncomment the lines.