qml中ComboBox组件onCurrentIndexChanged与onActivated的使用

在qml页面中使用ComboBox时,一般会有以下用法:

json 复制代码
ComboBox{
	id: box
	model: yourBindingModel
	onCurrentIndexChanged: {   
		//业务代码
	}	
}  

通常不会有什么问题,切换下拉列表时触发onCurrentIndexChanged,然后执行业务代码。

但是,如果有

json 复制代码
currentIndex: yourBindingIndex

即给combox组件的currentIndex进行了数据绑定,那么在初始化UI时,如果yourBindingIndex有有效值,则会触发onCurrentIndexChanged,此时并不是我们手动操作下拉列表触发的,这种情况一般是预期以外的,onCurrentIndexChanged内业务代码的执行也会造成程序异常。那如何避免呢?

使用onActivated

json 复制代码
onActivated: {}

看官方文档描述:

This signal is similar to currentIndex changed, but will only be emitted if the combo box index was changed by the user, not when set programmatically.

index is the activated model index, or -1 if a new string is accepted.

The corresponding handler is onActivated.

相关推荐
努力实干4 小时前
Qt/C++ 模块化设计与工程组织
开发语言·c++·qt
Lhan.zzZ4 小时前
Qt:动态库模块框架设计
开发语言·c++·qt
qq_401700411 天前
TCP 长连接、心跳包与断线自动重连设计:工业级通信的“不死鸟”架构
网络·qt·tcp/ip
dyxal2 天前
A2A 协议 v1.0 完全指南:方法名、Agent Card、三种绑定与 FastAPI 实战
开发语言·qt·fastapi
金色熊族2 天前
在Qt中使用asan检测内存泄漏(一)
linux·qt·asan
前行中的小猪2 天前
Qt 5 踩坑实录:多显示器跨屏拖拽导致窗口异常放大与 setGeometry 报错的深度解析与根治
qt·多显示器·高分辨率·多屏幕
想做小南娘,发现自己是女生喵2 天前
QT项目实战第一周(嵌入式)
开发语言·qt
誰能久伴不乏2 天前
【无标题】
c++·qt·机器人
金色熊族2 天前
在Qt中使用asan检测内存泄漏(二)--检查依赖库的内存使用
linux·qt·asan
qq_401700412 天前
Qt 组播(Multicast)实战详解
开发语言·qt