开发者

PyQt - how can element exist without pointer?

开发者 https://www.devze.com 2023-03-08 06:32 出处:网络
This program shows window and 3 buttons. Buttons are generated by iteration for i in range(3):. I don\'t understand this:

This program shows window and 3 buttons.

Buttons are generated by iteration for i in range(3):.

I don't understand this:

If button in the end only contains last button, where are all other buttons?

Why they are not deleted, when button starts referring to other element?

import sys
from PyQt4.QtGui import *

class MainWindow(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.vbox = QVBoxLayout()

        for i in range(3):
            button = QPushButton(str(i), self)
            self.vbox.addWidget(button)

        self.setLayout(self.vbox)

app = QApplication(sys.argv)
myapp = MainWindow()
myap开发者_运维问答p.show()
sys.exit(app.exec_())

To what all buttons are attached?

And how I can access them? button for last created button, but other buttons?


A reference to the button is held in the 'vbox' object.


By calling addWidget you "attach" the button to the view and this view stores some reference to its children. If you want to access them from your script, I would suggest you safe them as a local (or instance) variable.

Something like:

class MainWindow(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.vbox = QVBoxLayout()
        self.buttons = []

        for i in range(3):
            button = QPushButton(str(i), self)
            self.vbox.addWidget(button)
            self.buttons += [button]

        self.setLayout(self.vbox)


You can use the itemAt method of the QLayout class (which is a parent class of VBoxLayout) to get instances of QlayoutItems. The QLayoutItem class has a method widget which you can use to get the widgets you added.

For example in the below code snippet the call to items' method inMainWindowwould print text string of theQPushButton`'s you added (i.e. 0,1,2).

class MainWindow(QWidget):
    def __init__(self, parent=None):
        # same as the posted code

    def items(self):
        for i in range(self.vbox.count()):
            item  = self.vbox.itemAt(i)
            print item.widget().text()

app = QApplication(sys.argv)
myapp = MainWindow()
myapp.show()
myapp.items()
sys.exit(app.exec_()

0

精彩评论

暂无评论...
验证码 换一张
取 消