Sciter之子线程更新UI(八)

Sciter之子线程更新UI(八)

通常gui框架主线程负责更新UI,子线程可以通过post方法到主线程更新UI,子线程无法直接更新UI

本文章将介绍在子线程中更新UI、操作dom等,适用于耗时任务场景,例如子线程下载文件,完成后更新UI。

前言

Sciter 是一个高质量但小众的嵌入式 UI 引擎,适合追求性能、体积和原生集成的桌面应用开发者。

我觉得 Sciter 比较有意思,它很小众,是闭源的,商用需要许可。它是Andrew Fedoniouk开发维护,Andrew获得了物理学和应用数学硕士学位以及艺术文凭。他的职业生涯始于俄罗斯航空航天工业的研究员。这种跨领域背景使他既具备深厚的技术功底,又懂得用户界面设计的艺术。

本次入门开发环境:window 10 + Clion 2024.3 + Sciter-js v6.0.2.28(2025-11-15最新版) + Bundled MinGW 11.0 不了解的同学可以参考入门:https://lingkang.top/archives/sciter-ru-men-zhi-hello-yi

Sciter子线程中更新UI

在子线程中调用 sciter::thread线程即可更新UI,例如

c++后端

c 复制代码
// sciter::window 创建时全局存储好
sciter::window *global_window;

// main 中:
// 创建ui窗口实例
sciter::om::hasset<mainWindow> window = new mainWindow();
// set global
global_window = window;


// 方法中执行线程逻辑如下.......

std::string data="我要更新UI";

// 定义一个线程
std::thread([data](){
	Sleep(5000);// 模拟子线程延迟
	
	// 逻辑处理完毕,sciter::thread线程更新UI
	sciter::thread([data](sciter::window *win) {
		sciter::dom::element root = win->root();
		sciter::value json;
		json.set_item("type", "updateUI");
		json.set_item("data", data);
		root.post_event(L"cxx_event", json);// 发送事件通知
	}, global_window);// global_window 为sciter::window 创建时全局存储好
	
}).detach();// 剥离线程

html 前端

js 复制代码
// 监听c++发送的事件
Window.this.on("cxx_event", function (event) {
	const data = event.data
	console.log(data)
	// 根据数据做出不同更新操作
})

其他

除了上面使用事件通知前端更新,你还可以:

sciter::thread 调用方法更新:

c++

c 复制代码
// 逻辑处理完毕,sciter::thread线程更新UI
sciter::thread([data](sciter::window *win) {
	// 入参,只有一个
	VALUE argvs[1];
	LPCWSTR chars = L"入参字符串:lingkang";
	ValueStringDataSet(&argvs[0], chars, wcslen(chars), 0);
	VALUE result;
	// 调用前端js定义的 my_js_fun 方法
	SCDOM_RESULT ok = SciterCallScriptingFunction(win->root(), "my_js_fun", argvs, 1, &result);
	if (ok == SCDOM_OK) {
	   LPCWSTR str_data;
	  UINT str_length;
	  ValueStringData(&result, &str_data, &str_length);
		// 获取字符串数据
		std::wcout << "调用js的结果: " << str_data << std::endl;
	} else {
		// 处理错误
		std::cout << "调用js出错啦 " << std::endl;
	}

	// 清理
	ValueClear(&result);
	ValueClear(&argvs[0]);
}, global_window);// global_window 为sciter::window 创建时全局存储好

前端如下

js 复制代码
// 定义一个js方法给c++调用
function my_js_fun(param) {
	console.log('js方法被调用' + param);
	return '你的入参是:' + param
}

本文出自:https://lingkang.top/archives/sciter-thread-update-ui

相关推荐
端平入洛10 小时前
delete又未完全delete
c++
端平入洛1 天前
auto有时不auto
c++
哇哈哈20212 天前
信号量和信号
linux·c++
多恩Stone2 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马2 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝2 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc2 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
问好眼2 天前
《算法竞赛进阶指南》0x01 位运算-3.64位整数乘法
c++·算法·位运算·信息学奥赛
yyjtx2 天前
DHU上机打卡D31
开发语言·c++·算法
czxyvX2 天前
020-C++之unordered容器
数据结构·c++