学习在线示例我设法将一个自定义小部件添加到PyQT4中的列表框中,这是自定义小部件progress.py
的代码:
from PyQt4 import QtCore, QtGui, QtWebKit
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_(QtGui.QWidget):
def __init__(self, name, parent=None):
super(QtGui.QWidget,self).__init__(parent)
self.layoutWidget = QtGui.QWidget()
self.layoutWidget.setGeometry(QtCore.QRect(0, 0, 611, 31))
self.layoutWidget.setObjectName(_fromUtf8("layoutWidget"))
self.gridLayout = QtGui.QGridLayout(self.layoutWidget)
self.gridLayout.setMargin(0)
self.gridLayout.setSpacing(10)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.progressBar = QtGui.QProgressBar(self.layoutWidget)
self.progressBar.setProperty("value", 0)
self.progressBar.setObjectName(_fromUtf8("progressBar"))
self.gridLayout.addWidget(self.progressBar, 0, 1, 1, 1)
self.gridLayout.addWidget(self.graphicsView, 1, 1, 1, 1)
self.webView = QtWebKit.QWebView(self.layoutWidget)
self.webView.setGeometry(QtCore.QRect(0, 0, 500, 200))
self.webView.setUrl(QtCore.QUrl(_fromUtf8("about:blank")))
self.webView.setObjectName(_fromUtf8("webView"))
self.gridLayout.addWidget(self.webView, 1, 1, 1, 1)
QtCore.QMetaObject.connectSlotsByName(self)
#self.label.setText(_translate("", name, None))
self.webView.setHtml(name)
self.setLayout(self.gridLayout)
我使用以下代码从main.py
添加和填充此自定义窗口小部件:
def on_info_ready(self, data):
info = data.split("\n")
item = QtGui.QListWidgetItem(self.ui.listWidget)
makeHtml = "<h1>" + info[1] + "</h1>"
item_widget = progress.Ui_(makeHtml)
item.setSizeHint(item_widget.sizeHint())
self.ui.listWidget.addItem(item)
self.ui.listWidget.setItemWidget(item,item_widget)
以上工作完美,但我无法弄清楚如何访问上面添加的自定义窗口小部件作为列表项附加的进度条控件。我尝试了下面的多种变体,但它失败了:
def on_progress(self, data):
print (data)
self.ui.listWidget.item(0).progressBar.setValue(data)
以上代码错误地显示为:
Traceback (most recent call last): File "C:\Users\kk\Desktop\py4 gui\main.py", line 105, in on_progress self.ui.listWidget.item(0).progressBar.setValue(data) AttributeError: 'QListWidgetItem' object has no attribute 'progressBar' 0.0 Traceback (most recent call last): File "C:\Users\kk\Desktop\py4 gui\main.py", line 105, in on_progress self.ui.listWidget.item(0).progressBar.setValue(data) AttributeError: 'QListWidgetItem' object has no attribute 'progressBar' 0.0
答案 0 :(得分:1)
使用QListWidget.itemWidget
获取您使用QListWidget.setItemWidget
设置的小部件。
替换以下行:
self.ui.listWidget.item(0).progressBar.setValue(data)
使用:
widget = self.ui.listWidget.itemWidget(self.ui.listWidget.item(0))
widget.progressBar.setValue(data)