Search code examples
pythonpyqt5pyside2

Cannot align top QTableWidget in QVBoxLayout


I want to align both a QLabel and a QTableWidget in a QVBoxLayout on the top.

I have no problem aligning a QLabel on top to the QVBoxLayout by using the setAlignment method. When I add a QTableWidget to the QVBoxLayout, there is an issue.

My code:

class AWidget(QWidget):

    def __init__(self):
        super().__init__()

        self.aLabel = QLabel('Table')

        self.aTable = QTableWidget(6, 6)
        self.aTable.setMaximumHeight(200)

        self.aLayout = QVBoxLayout()
        self.aLayout.addWidget(self.aLabel)
        self.aLayout.addWidget(self.aTable)
        self.aLayout.setAlignment(Qt.AlignTop)
        self.setLayout(self.aLayout)

app = QApplication([])

aWidget = AWidget()
aWidget.resize(640, 480)
aWidget.show()

sys.exit(app.exec_())

The QLabel must be on top of the main widget followed by the QTableWidget below it. However, both the QLabel and the QTableWidget keep staying on the center of the main widget, leaving much spaces between them.


Solution

  • You fixed the maximum height of your table to 200px and the layout is dealing with it by occupying as much space as possible.

    You want to keep this height, you can insert a stretch at the end of your layout:

    class AWidget(QWidget):
    
        def __init__(self):
            super().__init__()
    
            self.aLabel = QLabel('Table')
    
            self.aTable = QTableWidget(6, 6)
            self.aTable.setMaximumHeight(200)
    
            self.aLayout = QVBoxLayout()
            self.aLayout.setAlignment(Qt.AlignTop)
            self.aLayout.addWidget(self.aLabel)
            self.aLayout.addWidget(self.aTable)
            self.aLayout.addStretch() # Adding a stretch to occupy the empty space
            self.setLayout(self.aLayout)