PyQt - how can element exist without pointer?
This program shows window and 3 buttons.
Buttons are generated by iterationfor i in range(3):
.
I don't understand this:
Ifbutton
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 in
MainWindowwould print text string of the
QPushButton`'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_()
精彩评论