pythonpyqt5qpushbuttonqvboxlayout

how to display 2 buttons and 2 labels using pyqt5 in python?


I want to display in a QWidget windows 2 buttons and 2 label where the 2 buttons as on the same horizontal layout. and each button will have under it the label.

For this i use to library :

When i run the script it doesn't display all the created widgets.

it display 1 button and 1 label.

code:

import sys
from PyQt5 import QtWidgets

def basicWindow():
    app = QtWidgets.QApplication(sys.argv)
    windowExample = QtWidgets.QWidget()
    buttonA = QtWidgets.QPushButton('Click!')
    labelA = QtWidgets.QLabel('Label Example')
    buttonb = QtWidgets.QPushButton('Click 2!')
    labelb = QtWidgets.QLabel('Label Example 2')
    

    v_box_H = QtWidgets.QHBoxLayout()
    # v_box_H2 = QtWidgets.QHBoxLayout()

    v_box = QtWidgets.QVBoxLayout()
    v_box.addWidget(buttonA)
    v_box.addWidget(labelA)

    v_box2 = QtWidgets.QVBoxLayout()
    v_box2.addWidget(buttonb)
    v_box2.addWidget(labelb)
    
    v_box_H.addLayout(v_box)
    

    windowExample.setLayout(v_box)
    windowExample.setLayout(v_box2)

    windowExample.setWindowTitle('PyQt5 Lesson 4')
    windowExample.show()

    sys.exit(app.exec_())

basicWindow()

Solution

  • If you run the application from terminal / CMD you get the error:

    QWidget::setLayout: Attempting to set QLayout "" on QWidget "", when the QLayout already has a parent
    

    Try it:

    import sys
    from PyQt5 import QtWidgets
    
    def basicWindow():
        app = QtWidgets.QApplication(sys.argv)
        
        windowExample = QtWidgets.QWidget()
        buttonA = QtWidgets.QPushButton('Click!')
        labelA = QtWidgets.QLabel('Label Example')
        buttonb = QtWidgets.QPushButton('Click 2!')
        labelb = QtWidgets.QLabel('Label Example 2')
        
    
        v_box_H = QtWidgets.QHBoxLayout(windowExample)    # + windowExample
        # v_box_H2 = QtWidgets.QHBoxLayout()
    
        v_box = QtWidgets.QVBoxLayout()
        v_box.addWidget(buttonA)
        v_box.addWidget(labelA)
    
        v_box2 = QtWidgets.QVBoxLayout()
        v_box2.addWidget(buttonb)
        v_box2.addWidget(labelb)
        
        v_box_H.addLayout(v_box)
        v_box_H.addLayout(v_box2)                          # +++
    
    #    windowExample.setLayout(v_box)                    # -
    #    windowExample.setLayout(v_box2)                   # -
    
        windowExample.setWindowTitle('PyQt5 Lesson 4')
        windowExample.show()
    
        sys.exit(app.exec_())
    
    basicWindow()
    

    enter image description here