> Learn from the previous article [pyqt model/view framework 1. first model] (http://www.cnblogs.com/hangxin1940/archive/2012/12/07/2806444.html), we can now simply display data through model/view, in this article, we will learn how to control View display by Delegate (delegate)
My first delegate
---
Add the following classes to the [previous] (http://www.cnblogs.com/hangxin1940/archive/2012/12/07/2806444.html) completed Code:
Class mydelegate (qstyleditemdelegate ):
"""
Custom delegate
Used to render the data once before the view is displayed after the model is obtained.
"""
Def paint (self, painter, option, index ):
"""
Paint, with a canvas paint brush, how to display it as needed, what to draw according to your own ideas
"""
# First, obtain the data from the index. Here, the data with the current index role displayqole is obtained.
Item_var = index. Data (QT. displayrole) # [qvariant]
# The data is in the C format, and we convert it to the python format. Remember this.
Item_str = item_var.topyobject () # [qvariant]-> Str
# We will display the data as a progress bar
Opts = qstyleoptionprogressbarv2 ()
Opts. rect = option. rect # size of the rectangle occupied by the progress bar
Opts. Minimum = 0
Opts. Maximum = 100
Opts. Text = STR (item_str) # displayed content
Opts. textalignment = QT. aligncenter
Opts. textvisible = true
Opts. Progress = int (item_str) # set the current progress
# This is the key
# Let the qapplication render and draw the control based on the current style
Qapplication. style (). drawcontrol (qstyle. ce_progressbar, opts, painter)
And change the content of the 'main () 'method:
Def main ():
APP = qapplication (SYS. argv)
# Create a custom Model
Model = mylistmodel ()
# Create a new delegate (delagate)
Delegate = mydelegate ()
# Creating a listview
View = qlistview ()
# Set the view Model
View. setmodel (model)
# Set the view's delegate
View. setitemdelegate (delegate)
View. Show ()
Sys.exit(app.exe C _())
After running, the data is displayed as a progress bar, which is the role of delegate.
> [Next] (http://www.cnblogs.com/hangxin1940/archive/2012/12/07/2806450.html), we'll learn how to present editable data in the view