Pregunta

I have the following code, but wanted to know how i could start at say 'Question x' where x is a random integer inputted by the user. i.e. how would i start from the 2nd question or 3rd question rather than question 1. Also if i was to start at say question 2, then question 1 shouldn't be shown at all. similarly if i was to start at question 3, then question 1 and 2 shouldn't be included/shown at all (regardless of first-last position).

Code

import sys
from PyQt4 import QtCore, QtGui

class StartTest(QtGui.QMainWindow):
    def __init__(self, questions, parent=None):
        super(StartTest, self).__init__(parent)
        self.stack = QtGui.QStackedWidget(self)
        self.setCentralWidget(self.stack)
        for index, question in enumerate(questions):
            page = Question(question, self)
            page.submit.clicked[()].connect(
                lambda index=index: self.handleSubmit(index))
            self.stack.addWidget(page)
        self.answers = []

    def handleSubmit(self, index):
        page = self.stack.widget(index)
        answer = page.answer.text()
        # validate submitted answer...
        self.answers.append(answer)
        if index < self.stack.count() - 1:
            self.stack.setCurrentIndex(index + 1)

class Question(QtGui.QWidget):
    def __init__(self, question, parent=None):
        super(Question, self).__init__(parent)
        self.question = QtGui.QLabel(question, self)
        self.answer = QtGui.QLineEdit(self)
        self.submit = QtGui.QPushButton('Submit', self)
        form = QtGui.QFormLayout()
        form.addRow(self.question, self.answer)
        layout = QtGui.QVBoxLayout(self)
        layout.addLayout(form)
        layout.addWidget(self.submit)

if __name__ == '__main__':
    User = ''
    app = QtGui.QApplication([])
    questions = [
        'What is 5+5?',
        'What is 45+10?',
        'What is 28+47?',
        'What is 22+13?',
        ]
    window = StartTest(questions)
    window.show()
    app.exec_()
¿Fue útil?

Solución

window = StartTest(questions[start_num:])

where you define start_num as the starting question, index beginning at 0. So, question 1 would be start_num of 0.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top