我如何使用While / For循环来创建类? (Python的/ PyQt的)

时间:2014-04-14 18:15:05

标签: python pyqt pyqt4

我创建了代码来创建具有不同类名的多个类(即问题1,问题2等)。

import sys
from PyQt4 import QtCore, QtGui

class StartTest(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(StartTest, self).__init__(parent)
        self.central_widget = QtGui.QStackedWidget()
        self.setCentralWidget(self.central_widget)
        question1 = Question1(self)
        self.central_widget.addWidget(question1)
        self.central_widget.setCurrentWidget(question1)
        question1.proceed.clicked.connect(self.question2)
    def question2(self):
        question2 = Question2(self)
        self.central_widget.addWidget(question2)
        self.central_widget.setCurrentWidget(question2)
i = 0
while i<2:
    class Question+i(QtGui.QWidget):
        def __init__(self, parent=None):
            super(Question+i, self).__init__(parent)
            question = QtGui.QLabel('What is 5+5?')
            self.proceed = QtGui.QPushButton("Proceed")
            self.Answer = QtGui.QLineEdit(self)
            layout = QtGui.QFormLayout()
            layout.addRow(question, self.Answer)
            layout2 = QtGui.QVBoxLayout()
            layout2.addLayout(layout)
            layout2.addWidget(self.proceed)
            self.setLayout(layout2)
            print('Question'+i)

if __name__ == '__main__':
    User = ''
    app = QtGui.QApplication([])
    window = StartTest()
    window.showFullScreen()
    app.exec_()

然而,当我写道:

i = 0
while i<2:
    class Question+i(QtGui.QWidget):

我在Question+i部分错误上获得了语法错误,这是错误的。但是我如何克服这一点,同时仍然创建具有不同类名的多个类???

1 个答案:

答案 0 :(得分:0)

请参阅this related question,了解如何动态设置类名。

您需要实现工厂方法。对你来说,它可能看起来像这样:

def factory(num) :
    BaseClass = QtGui.QWidget
    class NewClass(BaseClass): pass
    NewClass.__name__ = "factory_%s%d" % (BaseClass.__name__,  num)
    return NewClass