• Qt6.2.4 qDebug() 输出到控件


    参考

    环境

    环境 版本
    windows 10
    Qt 6.2.4
    Qt Creator 8.0.1 (Community)
    qmake

    一句话总结

    通过给 qInstallMessageHandler() 传入一个方法(main.cpp)或静态方法(控件中) 将 qDebug() 内容输出到窗口。其中静态方法需要解决的问题是获取控件实例,通过在类构造函数中给静态属性赋值的方式。

    代码

    mainwindow.h

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    
    #include "configtool.h"
    #include "loadwamp.h"
    #include "servicetool.h"
    
    #include <QMainWindow>
    #include <QSystemTrayIcon>
    #include <QCloseEvent>
    #include <QList>
    #include <QFileInfo>
    #include <QComboBox>
    #include <QString>
    
    QT_BEGIN_NAMESPACE
    namespace Ui { class MainWindow; }
    QT_END_NAMESPACE
    
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        MainWindow(QWidget *parent = nullptr);
        ~MainWindow();
        static void appendLogToEdit(QtMsgType type, const QMessageLogContext &context, const QString &msg);
    
    private slots:
    
    private:
        Ui::MainWindow *ui;
        // 声明自身静态属性来保存实例指针
        static MainWindow *mainWindow;
    };
    #endif // MAINWINDOW_H
    
    

    mainwindow.cpp

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QCoreApplication>
    #include <QDebug>
    #include <QString>
    #include <QUrl>
    #include <QDesktopServices>
    #include <QMainWindow>
    #include <QSystemTrayIcon>
    #include <QIcon>
    #include <QMenu>
    #include <QAction>
    #include <loadwamp.h>
    #include <QFileInfo>
    #include <QList>
    #include <configtool.h>
    #include <QComboBox>
    #include <QProcess>
    
    // 初始化静态属性
    MainWindow *MainWindow::mainWindow = NULL;
    
    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
        , ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        // 静态属性赋值
        MainWindow::mainWindow = this;
        // 注册日志方法
        qInstallMessageHandler(appendLogToEdit);
    //    qInstallMessageHandler([&](QtMsgType type, const QMessageLogContext &context, const QString &msg) -> void {
    //        ui->showLogEdit->append(msg);
    //    });
    }
    
    /**
     * @brief MainWindow::appendLogToEdit
     * @param rowLog
     * 追加显示日志到 edit中
     */
    void MainWindow::appendLogToEdit(QtMsgType type, const QMessageLogContext &context, const QString &msg)
    {
        if(MainWindow::mainWindow != NULL){
            MainWindow::mainWindow->ui->showLogEdit->append(msg);
        }
    }
    
    
    
  • 相关阅读:
    进程同步中的读者写者问题
    操作系统进程同步习题记录
    基于Python Flask的web日程管理系统
    面向对象第四单元及课程总结博客
    Vimtutor(中文版)学习笔记各章小结
    常用设计模式汇总说明
    图解Apache Mina
    Rocketmq 集群
    读《图解HTTP》有感-(HTTP首部)
    读《图解HTTP》有感-(与HTTP协作的WEB服务器)
  • 原文地址:https://www.cnblogs.com/xiaqiuchu/p/16729250.html
Copyright © 2020-2023  润新知