首页 > 解决方案 > 如何在pyqt5中添加可折叠按钮

问题描述

我需要创建一个包含几个按钮的可折叠按钮的 gui。有什么方法可以将可折叠小部件添加到 PyQt5 的主布局中?没有可用的适当文档。我已经创建了树小部件,但它显示为可滚动按钮,如第二张图片所示。在下面附上预期的结果和代码。

 import sys
 from PyQt5.QtWidgets import  QApplication, QWidget, QPushButton, 
 QAction,QMainWindow,QDialog,QTreeWidget, QTreeWidgetItem,  QLabel,  QVBoxLayout,  QLineEdit
 from PyQt5.QtGui import QIcon

 from PyQt5.QtCore import pyqtSlot
 from PyQt5 import QtCore, QtGui, QtWidgets
 from dld import TreeWidgetWithWidgetItems

 class App(QMainWindow,QWidget):

  def __init__(self):
    super().__init__()
    self.title = 'Status bar'
    self.left = 10
    self.top = 10
    self.width = 640
    self.height = 480
    self.initUI()

  def initUI(self):

    self.setWindowTitle(self.title)
    self.setGeometry(self.left, self.top, self.width, self.height)
    self.statusBar().showMessage('Message in statusbar.')
    mainMenu=self.menuBar()
    fileMenu=mainMenu.addMenu('File')
    confMenu = mainMenu.addMenu('Configure')
    aboutMenu = mainMenu.addMenu('About')
    exitButton = QAction('Exit', self)
    exitButton.setShortcut('Ctrl+Q')
    exitButton.setStatusTip('Exit application')
    exitButton.triggered.connect(self.close)
    fileMenu.addAction(exitButton)
    button = QPushButton('PyQt5 button', self)
    button.setToolTip('This is an example button')
    button.move(10, 60)
    button.clicked.connect(self.on_click)
# Creating top level and child widgets
    tLB = QPushButton("Top Level Button",self)
    # tLB.move(10,130)
    cB1 = QPushButton("Child 1",self)
    # cB1.move(40,60)
    cB2 = QPushButton("Child 2",self)
    # cB2.move(30,100)
    cB3 = QPushButton("Child 3",self)
    # cB3.move(40,150)
    childLineEdit = QLineEdit()
    childItems=[]
    treeWidget = QTreeWidget(self)
    treeWidget.move(10, 150)
    treeWidget.setHeaderLabel("TreeWidget with Buttons")
    topLevelItem = QTreeWidgetItem()
    for i in range(4):
        childItems.append(QTreeWidgetItem())

        topLevelItem.addChild(childItems[i])
    treeWidget.addTopLevelItem(topLevelItem)
    treeWidget.setItemWidget(topLevelItem, 0, tLB)
    # Replacing the child items with widgets
    treeWidget.setItemWidget(childItems[0], 0, cB1)
    treeWidget.setItemWidget(childItems[1], 0, cB2)
    treeWidget.setItemWidget(childItems[2], 0, cB3)

    self.show()

  @pyqtSlot()
  def on_click(self):
    print('PyQt5 button click')

if __name__ == '__main__':
   app = QApplication(sys.argv)
   MainWindow = QtWidgets.QMainWindow()



   ex = App()

   sys.exit(app.exec_())

第二张图片中包含菜单栏的预期输出

输出

标签: pythonuser-interfacepyqt5

解决方案


推荐阅读