Pyside2:如何添加动态布局和小部件?蟒蛇

时间:2020-05-29 07:37:08

标签: python layout dynamically-generated pyside2

我尝试同时动态添加按钮和布局。

将诸如按钮之类的窗口小部件放置在布局中对于以下行不是问题:self.hbox_l1.addWidget(self.btn)

但是如何通过变量将小部件放置在布局中?

import sys
from PySide2 import QtWidgets, QtGui


class Window(QtWidgets.QMainWindow):
    def __init__(self, parent = None):
        super().__init__()        
        self.setGeometry(300,200,500,400)
        self.create_layout()
        self.create_widget()
        self.show()

    def create_layout(self):
        self.main = QtWidgets.QVBoxLayout()
        self.hbox_l1 = QtWidgets.QHBoxLayout()        
        self.hbox_l2 = QtWidgets.QHBoxLayout()
        self.hbox_l3 = QtWidgets.QHBoxLayout()

        self.main.addLayout(self.hbox_l1)
        self.main.addLayout(self.hbox_l2)
        self.main.addLayout(self.hbox_l3)

    def create_widget(self):
        QtWidgets.QToolTip.setFont(QtGui.QFont('SansSerif', 20))
        newfont = QtGui.QFont("Times", 24, QtGui.QFont.Bold) 

        buttons = {'bouton1': ['hbox_l1', 'toolTip01'],
            'bouton2': ['hbox_l1', 'toolTip02'],
            'bouton3': ['hbox_l2', 'toolTip03'],
            'bouton4': ['hbox_l2', 'toolTip04'],
            }

        for btn, values in buttons.items():
            print(btn, values[0], values[1])
            self.btn = QtWidgets.QPushButton(str(btn))
            self.btn.setFont(newfont)
            self.btn.setToolTip(values[1])
            self.btn.clicked.connect(self.click_by_user)            
            # self.hbox_l1.addWidget(self.btn) --> Work perfect
            self.values[0].addWidget(self.btn)

        self.widget = QtWidgets.QWidget()
        self.widget.setLayout(self.main)
        self.setCentralWidget(self.widget)

    def click_by_user(self):
        print("Hello world")

myapp = QtWidgets.QApplication(sys.argv)
window = Window()

myapp.exec_()
sys.exit()

感谢您的帮助。 克里斯托夫(Christophe)

0 个答案:

没有答案