user6565581
user6565581

Reputation:

Layout in PyQt consists of QWidgetItems instead of QPushButtons and has no atribute text

I create a layout and put there 4 buttons via for loop.

layout = QtGui.QVBoxLayout()
my_list = ['1', '2', '3', '4']
for elem in my_list:
        button = QtGui.QPushButton(elem)
        layout.addWidget(button)

Then I want to check if any button has a text that I determine in a variable VAR. If it so - do something.

items = (layout.itemAt(i) for i in range(layout.count())) #get list of items in lay

for w in items:
    print w
    #it gives <PyQt4.QtGui.QWidgetItem object at 0x031F65D0> * 4 
    #instead of QPushButton.

    VAR = '1'
    if w.text() == VAR : #Problem here.
        print 'I got what I want.'
        #the problem is that QWidgetItem has no atribute text.

Please, tell me how to get list of QPushButtons instead of QWidgetItems or any other solution for this problem.

Upvotes: 4

Views: 712

Answers (2)

ekhumoro
ekhumoro

Reputation: 120578

The documentation for QWidgetItem is quite clear. You just need to do:

for item in items:
    w = item.widget()

Upvotes: 2

Lorenzo Simonassi
Lorenzo Simonassi

Reputation: 535

When you create a pushbutton if want to set a text on it, you should do:

# create the button
self.MyPushButton = QtGui.QPushButton()

# set the object's name (like an ID)
 self.MyPushButton.setObjectName("pushButton_1")

# This is how you set a text on the pushbutton
self.MyPushButton.setText("this is the text")

#get a pushbutton text:
self.MyPushButton.text()

Upvotes: 0

Related Questions