# -*- coding: utf-8 -*-

import sys
import os
from PySide6.QtCore import Qt, QCoreApplication, qInstallMessageHandler, QtMsgType
from PySide6.QtWidgets import QApplication
from PySide6.QtQml import QQmlApplicationEngine, QQmlError


def qt_message_handler(mode, context, message):
    """
    自定义Qt消息处理器
    :param mode: 消息类型 (Info, Warning, Critical, Fatal)
    :param context: 消息上下文 (文件, 行号, 函数)
    :param message: 消息内容
    """
    if mode == QtMsgType.QtInfoMsg:
        log_level = "INFO"
    elif mode == QtMsgType.QtWarningMsg:
        # QML的报错通常是Warning类型
        log_level = "WARNING"
    elif mode == QtMsgType.QtCriticalMsg:
        log_level = "CRITICAL"
    elif mode == QtMsgType.QtFatalMsg:
        log_level = "FATAL"
    else:
        log_level = "DEBUG"

    log_message = f"{log_level}: {message} (file: {context.file}, line: {context.line}, function: {context.function})"
    
    print(log_message, file=sys.stderr)



if __name__ == '__main__':
    
    qInstallMessageHandler(qt_message_handler)
    
    app = QApplication(sys.argv)
    
    
    engine = QQmlApplicationEngine()
    engine.load('demo.qml')
    if not engine.rootObjects():
        sys.exit(-1)
    
    sys.exit(app.exec())