我想要一个QListView
,它可以显示自定义小部件。我想最好的方法是QItemDelegate
。不幸的是,我不太了解如何正确地将其子类化,以及如何实现paint()
方法,这似乎是最重要的方法。我找不到任何关于使用委托创建另一个小部件的信息。在
我已经尝试过在没有委托的情况下实现类似的功能,但效果并不理想,因为QListView
不应该显示小部件。在
import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
class Model(QtCore.QAbstractListModel):
def __init__(self, parent=None):
super(QtCore.QAbstractListModel, self).__init__(parent)
self._widgets = []
def headerData(self, section, orientation, role):
""" Returns header for columns """
return "Header"
def rowCount(self, parentIndex=QtCore.QModelIndex()):
""" Returns number of interfaces """
return len(self._widgets)
def data(self, index, role):
""" Returns the data to be displayed """
if role == QtCore.Qt.DisplayRole:
row = index.row()
return self._widgets[row]
def insertRow(self, widget, parentIndex=QtCore.QModelIndex()):
""" Inserts a row into the model """
self.beginInsertRows(parentIndex, 0, 1)
self._widgets.append(widget)
self.endInsertRows()
class Widget(QtGui.QWidget):
def __init__(self, parent=None, name="None"):
super(QtGui.QWidget, self).__init__(parent)
self.layout = QtGui.QHBoxLayout()
self.setLayout(self.layout)
self.checkbox = QtGui.QCheckBox()
self.button = QtGui.QPushButton(self)
self.label = QtGui.QLabel(self)
self.label.setText(name)
self.layout.addWidget(self.checkbox)
self.layout.addWidget(self.button)
self.layout.addWidget(self.label)
class Window(QtGui.QMainWindow):
def __init__(self, parent=None):
super(QtGui.QMainWindow, self).__init__(parent)
self.view = QtGui.QListView(self)
self.model = Model()
self.view.setModel(self.model)
self.setCentralWidget(self.view)
self.model.insertRow(
widget=Widget(self)
)
self.model.insertRow(
widget=Widget(self)
)
self.model.insertRow(
widget=Widget(self)
)
self.model.insertRow(
widget=Widget(self)
)
self.show()
app = QtGui.QApplication(sys.argv)
window = Window()
sys.exit(app.exec_())
那么,我需要如何实现一个委托来完成我想要的事情呢?在
下面是一个
QTableWidget
的示例,其中每一行都有一个按钮和文本。我定义了一个add_item
方法来一次添加一整行:插入一个新行,在第0列中放置一个按钮,在第1列中放置一个常规项。在奖励:如何知道用户点击了哪个按钮?按钮没有行属性,但我们可以在实例化按钮时创建一个,如下所示:
^{pr2}$问题是,如果对表排序或删除行,行号将不再匹配。因此,我们设置了一个“name”属性,与第1列中该项的文本相同。然后我们可以使用
findItems
来获得行(请参见on_click
)。在相关问题 更多 >
编程相关推荐