簡體   English   中英

訪問動態添加的小部件(pyqt)

[英]Accessing dynamically added widgets (pyqt)

我想將文本添加到使用基於此問題的可接受答案的按鈕添加的文本框中: 在pyqt中動態添加和刪除小部件

但是,我的問題是我無法訪問已添加的文本框。 這篇文章告訴我,當使用addWidget()添加到布局時,我可以使用itemAt()遍歷添加的項目。 但是我只能訪問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_()

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!')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM