PYQT5 + QML 之ListView

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_()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值