在PyQt / Pyside中使用动态添加的小部件

时间:2018-01-18 11:16:27

标签: pyqt widget pyside python-3.4

我修改了here给出的答案,如下所示。代码基本上是创建按钮,计数器为pushButton_0,pushButton_1 .. 在这里,我知道当我按下self.addButton时,我正在创建名为self.pushButton_0, self.pushButton_1等的小部件。所以,我的问题是,我应该如何使用这个按钮?因为当我尝试做self.pushButton_0.clicked.connect(self.x)之类的事情时,它告诉我“没有名为'pushButton_0'的属性。”

谢谢!

from PyQt4 import QtGui, QtCore
import sys

class Main(QtGui.QMainWindow):
    def __init__(self, parent = None):
        super(Main, self).__init__()
        self.GUI()


    def GUI(self):

        self.count = 0

        # main button
        self.addButton = QtGui.QPushButton('button to add other widgets')
        self.addButton.clicked.connect(self.addWidget)

        # scroll area widget contents - layout
        self.scrollLayout = QtGui.QFormLayout()

        # scroll area widget contents
        self.scrollWidget = QtGui.QWidget()
        self.scrollWidget.setLayout(self.scrollLayout)

        # scroll area
        self.scrollArea = QtGui.QScrollArea()
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setWidget(self.scrollWidget)

        # main layout
        self.mainLayout = QtGui.QVBoxLayout()

        # add all main to the main vLayout
        self.mainLayout.addWidget(self.addButton)
        self.mainLayout.addWidget(self.scrollArea)

        # central widget
        self.centralWidget = QtGui.QWidget()
        self.centralWidget.setLayout(self.mainLayout)

        # set central widget
        self.setCentralWidget(self.centralWidget)

    def addWidget(self):
        self.scrollLayout.addRow(Test(self))
        self.count = self.count + 1
        print(self.count)


class Test(QtGui.QWidget):

    def __init__( self, main):
        super(Test, self).__init__()
        self.Main = main
        self.setup()


    def setup(self):

        print(self.Main.count)

        name = "pushButton_"+str(self.Main.count)
        print(name)

        self.name = QtGui.QPushButton('I am in Test widget '+str(self.Main.count))


        layout = QtGui.QHBoxLayout()
        layout.addWidget(self.name)
        self.setLayout(layout)



app = QtGui.QApplication(sys.argv)
myWidget = Main()
myWidget.show()
app.exec_()

1 个答案:

答案 0 :(得分:1)

几小时后,我发现了问题!

您必须在创建按钮时声明信号! 为了解决这个问题,我重新编写了如下设置功能;

 def setup(self):

    print(self.Main.count)

    name = "pushButton_"+str(self.Main.count)
    print(name)

    self.name = QtGui.QPushButton('I am in Test widget '+str(self.Main.count))
    self.name.clicked.connect(self.x)        # self.x is any function



    layout = QtGui.QHBoxLayout()
    layout.addWidget(self.name)
    self.setLayout(layout)

所以要知道,只要按下新创建的按钮,就会运行x函数!