ShellRox ShellRox - 2 years ago 173
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 ):

if sendercheck == ( self.answ2 ):

How can I put
length in QLabel?

I have tried these:

self.wronganswerlabel = QtGui.QLabel(self)
self.wronganswerlabel.setGeometry(200, 200, 200, 200)

Gave me this error:


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)

Gave me error:

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

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

Answer Source

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 = QtGui.QLabel(self, "Score:" + str(len(wronganswers)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download