ShellRox ShellRox - 7 months ago 20
Python Question

Putting list length to QLabel in PyQt4

I have made Multi-Page Quiz application in PyQt4, I'm trying to add score summary at the end, so it will count how many correct and incorrect answers were there.

For that I have made lists, this is how I made it:

def scorecheck(self, sendercheck): # sendercheck object gets from which widget was signal sent.
wronganswers = []
correctanswers = []
if sendercheck == ( self.answ or self.answ1 ):
wronganswers.append(1)


if sendercheck == ( self.answ2 ):
correctanswers.append(1)





How can I put
wronganswers
length in QLabel?

I have tried these:

self.wronganswerlabel = QtGui.QLabel(self)
self.wronganswerlabel.setText(len(wronganswers))
self.wronganswerlabel.setGeometry(200, 200, 200, 200)
self.wronganswerlabel.show()


Gave me this error:


self.wronganswer.setText(len(wronganswers))

TypeError: QLabel.setText(QString): argument 1 has unexpected type 'int'


and this:

self.wronganswerlabel = QtGui.QLabel(self, "Score:".len(wronganswers))
self.wronganswerlabel.setGeometry(200, 200, 200, 200)
self.wronganswerlabel.show()


Gave me error:


self.wronganswer = QtGui.QLabel(self, "Score:".len(wronganswers))

AttributeError: 'str' object has no attribute 'len'

Answer

It's just a casting thing; QtGui.QLabel() and QtGui.QLabel.setText() expects a QtCore.QString or just a unicode or string object, but you are trying to pass an int. You need to tell python how to translate the integer into a string. The usual way is str(myint)

Additionally, you need to use the + operator to combine two strings -- the way you have the syntax now, you are asking the string "Score:" for it's length method, which is probably not what you meant.

The following should work as expected

self.wronganswerlabel.setText(str(len(wronganswers)))

OR

self.wronganswerlabel = QtGui.QLabel(self, "Score:" + str(len(wronganswers)))