Have a nice day
Have a nice day

Reputation: 1015

How can I position widgets inside a layout?

I'm having trouble with spacing widgets in a QVboxlayout. I have this code:

from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys


class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        win_w, win_h = 250, 1
        self.setGeometry((1920 - win_w) // 2, (1080 - win_h) // 2, win_w, win_h)
        self.setWindowTitle('Test')
        
        self.setFont(QtGui.QFont('Times', 12))
        
        self.central_widget()

    def central_widget(self):
        widget = QtWidgets.QWidget()
        grid = QtWidgets.QGridLayout()
        group_box1 = QtWidgets.QGroupBox('Group Box')
        v1 = QtWidgets.QVBoxLayout()
        text_edit1 = QtWidgets.QTextEdit()

        v1.addWidget(QtWidgets.QPushButton('Button'))
        v1.addWidget(text_edit1)
        
        group_box1.setLayout(v1)
        
        grid.addWidget(group_box1, 0, 0)
    
        widget.setLayout(grid)
        self.setCentralWidget(widget)
        
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())

Running this brings up this window:

enter image description here

Adding this line v1.setSpacing(100) changes it to this:

enter image description here

Is there any way to make it add the spacing horizontally? Like this:

enter image description here

Upvotes: 0

Views: 114

Answers (1)

musicamante
musicamante

Reputation: 48509

Use the alignment keyword argument for addWidget():

v1.addWidget(QtWidgets.QPushButton('Button'), alignment=QtCore.Qt.AlignRight)

As already suggested, you should carefully read the documentation about layout managers, including all the listed QLayout subclasses and all their methods. You can do some experiments on your own with them also in Designer, so that you can better understand how they work by directly seeing the results.

Upvotes: 1

Related Questions