简体   繁体   English

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

[英]How do i use a While/For loop to create classes?? (Python/PyQt)

I have created the code to create multiple classes with different class names (Ie Question1, Question2 etc.) 我已经创建了代码来创建具有不同类名的多个类(即Question1,Question2等)。

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

However when I write: 但是当我写:

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

i obtain a syntax error on the Question+i part error, which is undertandable. 我在Question+i部分错误中获得语法错误,这是可理解的。 But how would i overcome this whilst still creating multiple classes with different class names??? 但是在仍然创建具有不同类名的多个类的同时,我将如何克服这个问题呢?

See this related question with answers on how to set class names dynamically. 请参阅此相关问题,并提供有关如何动态设置类名称的答案。

You need to implement a factory method. 您需要实现一种工厂方法。 For you it might look like this: 对您来说,它可能像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM