访问动态添加的小部件 (pyqt)
Posted
技术标签:
【中文标题】访问动态添加的小部件 (pyqt)【英文标题】:Accessing dynamically added widgets (pyqt) 【发布时间】:2015-03-02 21:20:37 【问题描述】:我想将文本添加到文本框中,该文本框是我使用基于此问题接受的答案的按钮添加的:Dynamically adding and removing widgets in pyqt
但是,我的问题是我无法访问已添加的文本框。 This 帖子告诉我,我可以使用 itemAt()
来循环使用 addWidget()
添加到布局时添加的项目。但是我只能访问QWidgetIem
类型的“内部布局”
这是我的代码:-
from PyQt4 import QtGui, QtCore
import sys
class Main(QtGui.QMainWindow):
def __init__(self, parent = None):
super(Main, self).__init__(parent)
# main button
self.addButton = QtGui.QPushButton('button to add other widgets')
self.addButton.clicked.connect(self.addWidget)
# scroll area widget contents - layout
self.scrollLayout = QtGui.QHBoxLayout()
# scroll area widget contents
self.scrollWidget = QtGui.QWidget()
self.scrollWidget.setLayout(self.scrollLayout)
# scroll area
self.scrollArea = QtGui.QScrollArea()
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setWidget(self.scrollWidget)
# main layout
self.mainLayout = QtGui.QVBoxLayout()
# add all main to the main vLayout
self.mainLayout.addWidget(self.addButton)
self.mainLayout.addWidget(self.scrollArea)
# central widget
self.centralWidget = QtGui.QWidget()
self.centralWidget.setLayout(self.mainLayout)
# set central widget
self.setCentralWidget(self.centralWidget)
def addWidget(self):
self.scrollLayout.addWidget(Test())
# This doesn't work
print self.scrollLayout.itemAt(0)
class Test(QtGui.QWidget):
def __init__(self, parent=None):
super(Test, self).__init__(parent)
# Sensor Indicator
self.pushButton = QtGui.QPushButton()
self.pushButton.setStyleSheet("background-color: green")
# Console Window to display sensor data
self.logOutput = QtGui.QTextEdit()
self.logOutput.setReadOnly(True)
self.logOutput.setLineWrapMode(QtGui.QTextEdit.NoWrap)
self.font = self.logOutput.font()
self.font.setFamily("Courier")
self.font.setPointSize(10)
layout = QtGui.QVBoxLayout()
layout.addWidget(self.pushButton)
layout.addWidget(self.logOutput)
self.setLayout(layout)
app = QtGui.QApplication(sys.argv)
myWidget = Main()
myWidget.show()
app.exec_()
【问题讨论】:
【参考方案1】:QWidgetItem
有一个 widget()
函数用于检索它包含的对象:
def addWidget(self):
self.scrollLayout.addWidget(Test())
index = self.scrollLayout.count() - 1
widget = self.scrollLayout.itemAt(index).widget()
if widget is not None:
widget.logOutput.setText('Hello World!')
【讨论】:
以上是关于访问动态添加的小部件 (pyqt)的主要内容,如果未能解决你的问题,请参考以下文章