【问题标题】:Connecting QML to C++ slot将 QML 连接到 C++ 插槽
【发布时间】:2021-12-12 05:38:15
【问题描述】:

我创建了一个应用程序,每次加载程序的源发生变化时都会自动截屏!我正在尝试将 QML 信号 (screenshot()) 连接到 CPP 插槽 (take_screenshot())。但是,尽管加载程序的源正在更改并且我也收到了控制台日志,但从未调用过 take_screenshot() 函数!这是我的 cpp.h

 class MyClass : public QObject
 {
    Q_OBJECT
public:
MyClass(std::shared_ptr<QQmlApplicationEngine> engin)
    : m_engine(engin)
{
    QObject* root = m_engine->rootObjects()[0];
    Q_ASSERT(root != nullptr);
    QObject::connect(root, SIGNAL(screenshot()),
                     this, SLOT(take_screenshot()));
}

public slots:
int take_screenshot()
{
        QString currentDateTime = QDateTime::currentDateTime().toString( "MMMM d, yyyy, HH:mm:ss");
        QScreen *screen;
        QPixmap pixmap;
        screen = QGuiApplication::primaryScreen();
        pixmap = screen->grabWindow(0);
        QString screenshotPath = QDir::currentPath();
        QString screenShotFileName = QString("%1/%2.png").arg(screenshotPath).arg(currentDateTime);

        if (!screenShotFileName.isEmpty())
        {
            pixmap.save(screenShotFileName);
            return 1;
        }
        else
            return 0;
}

private:
std::shared_ptr<QQmlApplicationEngine> m_engine;
};

这是我的 main.qml

Window {
id: mainWindow
visible: true
width: 640
height: 480
title: qsTr("Hello World")

signal screenshot()
Loader {
         id: pageLoader
         objectName: "pageLoader"
         anchors.fill: parent
         onSourceChanged: {
         console.log("onSourceChanged_source :", pageLoader.source)
                mainWindow.screenshot()
            }
         Component.onCompleted:{
                console.log("onCompleted!", pageLoader.source)
                mainWindow.screenshot()
            }
        }
   }

【问题讨论】:

    标签: c++ qt qml signals-slots


    【解决方案1】:

    不要在 C++ 中访问 QML 对象,因为您可能会遇到意外行为。在这种情况下,最好将对象导出到 QML,例如创建一个单例:

    utils.h

    #ifndef UTILS_H
    #define UTILS_H
    
    #include <QGuiApplication>
    #include <QObject>
    #include <QPixmap>
    #include <QQmlApplicationEngine>
    #include <QScreen>
    #include <QDateTime>
    #include <QDir>
    
    class Utils : public QObject
    {
        Q_OBJECT
    public:
        using QObject::QObject;
    public slots:
        bool screenshot(){
            qDebug() << __PRETTY_FUNCTION__;
            QString currentDateTime = QDateTime::currentDateTime().toString( "MMMM d, yyyy, HH:mm:ss");
            QString screenshotPath = QDir::currentPath();
            QString filename = QString("%1/%2.png").arg(screenshotPath).arg(currentDateTime);
            if(QScreen *screen = QGuiApplication::primaryScreen()){
                QPixmap pixmap = screen->grabWindow(0);
                return pixmap.save(filename));
            }
            return false;
        }
    };
    #endif // UTILS_H
    

    main.cpp

    #include "utils.h"
    
    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    
    
    int main(int argc, char *argv[])
    {
    #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
        QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    #endif
    
        QGuiApplication app(argc, argv);
    
        QScopedPointer<Utils> utils(new Utils);
        qmlRegisterSingletonInstance("Utils", 1, 0, "Utils", utils.get());
    
        QQmlApplicationEngine engine;
    
        const QUrl url(QStringLiteral("qrc:/main.qml"));
        QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                         &app, [url](QObject *obj, const QUrl &objUrl) {
            if (!obj && url == objUrl)
                QCoreApplication::exit(-1);
        }, Qt::QueuedConnection);
        engine.load(url);
        return app.exec();
    }
    

    main.qml

    import QtQuick 2.15
    import QtQuick.Window 2.15
    
    import Utils 1.0
    
    Window {
        id: mainWindow
        visible: true
        width: 640
        height: 480
        title: qsTr("Hello World")
        Loader {
            id: pageLoader
            anchors.fill: parent
            onSourceChanged: {
                console.log("onSourceChanged_source :", pageLoader.source)
                Utils.screenshot()
            }
            Component.onCompleted:{
                console.log("onCompleted!", pageLoader.source)
                var res = Utils.screenshot()
                console.log(res)
            }
        }
    }
    

    【讨论】:

    • 这仍在调用mainWindow.screenshot()。我想你打算把它改成Utils.screenshot(),对吧?
    • @JarMan 哎呀。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多