【问题标题】:Layout in PyQt consists of QWidgetItems instead of QPushButtons and has no atribute textPyQt 中的布局由 QWidgetItems 而不是 QPushButtons 组成,并且没有属性文本
【发布时间】:2017-03-21 01:03:05
【问题描述】:

我创建了一个布局并通过 for 循环放置了 4 个按钮。

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

然后我想检查是否有任何按钮具有我在变量 VAR 中确定的文本。如果是这样 - 做点什么。

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.

请告诉我如何获取 QPushButtons 列表而不是 QWidgetItems 或任何其他解决此问题的方法。

【问题讨论】:

    标签: python button layout pyqt


    【解决方案1】:

    当你创建一个按钮时,如果想在它上面设置一个文本,你应该这样做:

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

    【讨论】:

    • 这不是我想要的,顺便说一句,我知道如何在按钮上设置文本。我有一个巨大的文件列表,我需要为其中的每个项目创建一个按钮。
    【解决方案2】:

    QWidgetItem 的文档非常清楚。你只需要这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-04
      • 1970-01-01
      相关资源
      最近更新 更多