如何截屏 Qt/QML

Posted

技术标签:

【中文标题】如何截屏 Qt/QML【英文标题】:How to take ScreenShot Qt/QML 【发布时间】:2013-06-13 14:44:19 【问题描述】:

QtQuick1 example 我无法让它在 QtQuick2 上运行

screenCapture.hpp

#include <QObject>

class QString;
class QQuickView;

class screenCapture : public QObject

    Q_OBJECT
public:    
    explicit screenCapture(QQuickView *parent = 0);

public slots:
    void capture(QString const &path) const;

private:
    QQuickView *currentView_;    
;

screenCapture.cpp

#include <QPixmap>
#include <QQuickView>
#include <QString>

#include "screenCapture.hpp"

screenCapture::screenCapture(QQuickView *currentView) :
    QObject(0), currentView_(currentView)



void screenCapture::capture(QString const &path) const

    QPixmap::grabWidget(currentView_).save(path);

main.cpp

#include <QGuiApplication>
#include <QQuickPaintedItem>
#include <QQuickView>
#include <QQmlContext>

#include "screenCapture.hpp"

int main(int argc, char *argv[])

    QGuiApplication app(argc, argv);

    qmlRegisterType<screenCapture>("Image", 1, 0, "ScreenCapture");
    qmlRegisterType<saveAbleImage>("Image", 1, 0, "SaveAbleImage");

    QQuickView view;
    view.setResizeMode(QQuickView::SizeRootObjectToView);
    view.setSource(QStringLiteral("/Users/Qt/program/experiment_apps_and_libs/funnyCamera/qml/funnyCamera/main.qml"));
    view.show();

    screenCapture screenClass(&view);
    view.rootContext()->setContextProperty("screenObject", &screenClass);

    return app.exec();

main.qml

import QtQuick 2.0

Rectangle
    id : root
    width : 1024
    height : 768    

    MouseArea
        anchors.fill: root

        onClicked:           
            console.log("save image")
            screenObject.capture("Pictures/saveTest.jpg")
        
    

错误信息

QPixmap::grabWidget 已弃用,请改用 QWidget::grab() QMetaObject::invokeMethod: 没有这种方法 QQuickView::grab(QRect)

【问题讨论】:

对于 Qt5 QML Quick2 你可以使用这个例子:***.com/questions/17146747/… 【参考方案1】:

我找到了一个解决办法,很简单,把函数“capture”改成

void screenCapture::capture(QString const &path) const

    QImage img = currentView_->grabWindow();
    img.save(path);

【讨论】:

以上是关于如何截屏 Qt/QML的主要内容,如果未能解决你的问题,请参考以下文章

QT / QML如何在地图上运行mapReady?

如何在 Qt QML 中创建多屏应用程序

QT/QML:模型没有数据时如何显示消息

Qt/Qml:如何包含地图瓦片以供离线使用?

Qt/QML:如何根据验证器找到 TextInput 最大宽度

如何使用qml qt3d(qt)将对象旋转一个角度?