【问题标题】:how to display 2 buttons and 2 labels using pyqt5 in python?如何在 python 中使用 pyqt5 显示 2 个按钮和 2 个标签?
【发布时间】:2020-09-02 08:13:35
【问题描述】:

我想在一个 QWidget 窗口中显示 2 个按钮和 2 个标签,其中 2 个按钮作为在相同的水平布局上。每个按钮下面都有标签。

为此我使用图书馆:

  • QHBoxLayout
  • QVBoxLayout

当我运行脚本时,它不会显示所有创建的小部件。

它显示 1 个按钮和 1 个标签。

代码:

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()

【问题讨论】:

    标签: python pyqt5 qpushbutton qvboxlayout


    【解决方案1】:

    如果您从终端/CMD 运行应用程序,则会收到错误:

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

    试试看:

    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()
    

    【讨论】:

      猜你喜欢
      • 2023-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      相关资源
      最近更新 更多