• 3071阅读
  • 3回复

zhengtianzuo系列-Qml写日志 [复制链接]

上一主题 下一主题
离线zhengtianzuo
 

只看楼主 倒序阅读 楼主  发表于: 2017-10-16
大家都知道通过Q_INVOKABLE可以让qml直接访问c++类的接口函数.

```
void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex mutex;
    mutex.lock();

    QString text;
    switch(type)
    {
    case QtDebugMsg:
        text = QString("Debug:");
        break;

    case QtWarningMsg:
        text = QString("Warning:");
        break;

    case QtCriticalMsg:
        text = QString("Critical:");
        break;

    case QtFatalMsg:
        text = QString("Fatal:");
    }

    QString message = "";
    if (context.file != nullptr)
    {
        QString context_info = QString("File:(%1) Line:(%2)").arg(QString(context.file)).arg(context.line);
        QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");
        QString current_date = QString("(%1)").arg(current_date_time);
        message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);
    }
    else
    {
        message = msg;
    }

    QFile file("log.txt");
    file.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream text_stream(&file);
    text_stream << message << "\r\n";
    file.flush();
    file.close();

    mutex.unlock();
}

QmlLog4Qml::QmlLog4Qml()
{
    qInstallMessageHandler(outputMessage);
}

void QmlLog4Qml::qDebug_Info(int type, QString strInfo)
{
    QMessageLogContext context;
    context.file = nullptr;
    outputMessage((QtMsgType)type, context, strInfo);
}
```



需要完整代码请访问 QtQuickExamples
博客地址: https://blog.csdn.net/zhengtianzuo06
Github: https://github.com/zhengtianzuo
个人产品: https://github.com/zhengtianzuo/Silk
产品网站: http://www.camelstudio.cn
离线ccazqyy

只看该作者 1楼 发表于: 2017-10-17
          
离线rpaul518

只看该作者 2楼 发表于: 2017-10-30
qml系列啊,老铁,牛!!!
fasdfasdfasdfasdfa
离线zhengtianzuo

只看该作者 3楼 发表于: 2017-10-31
回 rpaul518 的帖子
rpaul518:qml系列啊,老铁,牛!!![表情] [表情] [表情]  (2017-10-30 21:37) 

一起学习~
博客地址: https://blog.csdn.net/zhengtianzuo06
Github: https://github.com/zhengtianzuo
个人产品: https://github.com/zhengtianzuo/Silk
产品网站: http://www.camelstudio.cn
快速回复
限100 字节
 
上一个 下一个