Salah Eddine
Salah Eddine

Reputation: 155

How to add a child layout to parent layout?

I want to group two widgets in a QGridLayout so I can move them both at the same time as one widget in the parent Layout, I've red that the addLayout can the the work however I couldn't find a class with that name but instead I find addChildLayout and addChildWidget but I don't know how to make them work!

Here's the code I test on:

#!/usr/bin/env python3.5.2

from PyQt5.QtWidgets import*
from PyQt5.QtCore import*
import sys

class ClassName(QDialog):
    def __init__(self):
        QDialog.__init__(self)

        parent_layout = QGridLayout()

        self.text1 = QLineEdit()
        self.text2 = QLineEdit()
        # I want to make Button1, text3 and progress widgets in one line
        # I want Button1, text3 in a child_layout
        Button1 = QPushButton("Button1")
        self.text3 = QLineEdit()
        self.progress = QProgressBar()


        self.text1.setPlaceholderText("text 1")
        self.text1.setFixedWidth(524)

        self.text2.setPlaceholderText("text 2")
        self.text2.setFixedWidth(85)

        self.progress.setValue(0)
        self.progress.setAlignment(Qt.AlignHCenter)

        Button1.setFixedWidth(125)

        self.text3.setReadOnly(True)
        self.text3.setPlaceholderText("text 3")

        parent_layout.addWidget(self.text1, 0, 0)
        parent_layout.addWidget(self.text2, 0, 1)
        parent_layout.addWidget(self.progress, 1, 1)
        parent_layout.addWidget(Button1, 1, 0)
        parent_layout.addWidget(self.text3, 2, 0)

        self.setLayout(parent_layout)

app = QApplication(sys.argv)
dialog = ClassName()
dialog.show()
sys.exit(app.exec_())

Result:

enter image description here

What I want:

enter image description here

Upvotes: 0

Views: 3965

Answers (1)

hobenkr
hobenkr

Reputation: 1234

I believe what you want to do is set the columnspan argument when you call addWidget(). For example from your image, it looks like text1 should span two columns of your grid. If you take a look at the qt docs, you'll see that addWidget is overloaded and can accept the arguments rowSpan and columnSpan. Using that information, you should be able to populate your window like this.

parent_layout.addWidget(self.text1, 0, 0, 1, 2)
parent_layout.addWidget(self.text2, 0, 1)
parent_layout.addWidget(Button1, 1, 0)
parent_layout.addWidget(self.text3, 1, 1)
parent_layout.addWidget(self.progress, 1, 2)

Let me know if that works out.

Upvotes: 1

Related Questions