Search code examples
pythonpyqt5

Add layout inside QFrame()


I am beginner in the PyQt5

in my application I need to make (buttons, line edit, labels ...) in QVBoxLayout then puts everything on QFrame.

My Question: Is It possible to make a layout (QHBoxLayout, QVBoxLayout, QFormeLayout ....) inside a QFrame ?

If possible, please tell me how to do .


Solution

  • Use a text editor or Qt Designer to create an .ui file. Here is a minimal example:

    <widget class="QFrame" name="frame">
       <property name="geometry">
          <rect><x>60</x><y>40</y><width>160</width><height>100</height> 
    </rect>
       </property>
       <layout class="QVBoxLayout" name="verticalLayout">
          <item><widget class="QPushButton" name="pushButton" /></item>
          <item><widget class="QLabel" name="label" /></item>
          <item><widget class="QLineEdit" name="lineEdit"/></item>
       </layout>
    </widget>
    

    It will look something like this:

    enter image description here

    Python example:

    import sys
    from PySide6.QtWidgets import QApplication, QWidget, QFrame, QLabel, QLineEdit, QPushButton, QVBoxLayout, QSpacerItem
    app = QApplication(sys.argv)
    window = QWidget()
    window.setGeometry(300,300,300,100)
    frame = QFrame(window)
    layout = QVBoxLayout(frame)
    pushButton = QPushButton("pushButton")
    layout.addWidget(pushButton)
    label = QLabel("label")
    layout.addWidget(label)
    lineEdit = QLineEdit("lineEdit")
    layout.addWidget(lineEdit)
    window.show()
    app.exec()
    

    C++ example:

    void QtWidgetsApplication1::setupUi(QMainWindow* window) {
      
       frame = new QFrame(window);
       window->setCentralWidget(frame);
    
       verticalLayout = new QVBoxLayout(frame);
    
       pushButton = new QPushButton(frame);
       pushButton->setText("pushButton");
       verticalLayout->addWidget(pushButton);
    
       label = new QLabel(frame);
       label->setText("label");
       verticalLayout->addWidget(label);
    
       lineEdit = new QLineEdit(frame);
       lineEdit->setText("lineEdit");
       verticalLayout->addWidget(lineEdit);
    
       verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
       verticalLayout->addItem(verticalSpacer);
    }