pyqt5 + qml学习之ListView
ListView基本显示:
ListModel {
id: item_model
// 此处是初始化显示的例子
ListElement {
text: "Item 0"
}
ListElement {
text: "Item 1"
}
}
ListView {
id: lstMyView
model: item_model
}
ListView多属性显示。
比如显示一个网络发过来的消息,显示对方的名字和消息。当然,你可以把消息在Python端处理完,做成一条text发过来显示。但如果我们要第两行显示,并且让两行的颜色和字体都不一样时。那就只能用下面的方法了。
两个重要的属性,需要创建
delegate:这个是用于显示的控件。就是一个Widget
model:我理解成内容的打包。不太需要怎么处理
//delegate的创建
新建一个MyListItem.qml。内容如下
import QtQuick 2.2
import QtQuick.Controls 2.2
Item{
id: base
property string name: ""
property string msg: ""
height: 60 //每行的高度
Column {
// 用于显示对方名字
Text {
text: name
color: "blue"
font { pixelSize: 22}
}
// 用于显示消息
Text {
text: msg
color: "green"
font { pixelSize: 30}
}
}
}
//main.qml
import QtQuick 2.12
import QtQuick.Controls 2.12
//window containing the application
Rectangle {
id: top_window
visible: true
width: 600
height: 400
ListModel {
id: item_model
// 此处是初始化显示的例子
ListElement {
e_name: "LiLei"
e_msg: "How are you"
}
ListElement {
e_name: "HanMeimei"
e_msg: "I'm find, thank you"
}
}
ListView {
id: lstMyView
visible: true
x: 20
y: 20
width: 300
height: 200
model: item_model
delegate: MyListItem{
name: e_name
msg: e_msg
}
}
// 添加记录的函数
function addToList(who, word) {
item_model.append({ e_name:who, e_msg:word })
}
// 按下之后,新增一行记录
MouseArea {
x: 500
y: 350
width: 50
height: 50
Rectangle {
anchors.fill: parent
color: "#808080"
}
onClicked: {
console.log("btnn")
addToList("Lucy", "Nice to meet you")
}
}
}
main.py文件内容
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView
from PyQt5 import QtQml
from PyQt5.QtCore import QUrl
if __name__ == '__main__':
path = './main.qml'
app = QGuiApplication([])
view = QQuickView()
view.engine().quit.connect(app.quit)
view.setSource(QUrl(path))
view.show()
app.exec_()