qml 截屏主要使用QQuickWindow中grabWindow()完成,关于grabWindow()介绍如下亦可查看帮助所以不多说。
QImage QQuickWindow::grabWindow()
Grabs the contents of the window and returns it as an image.
It is possible to call the grabWindow() function when the window is not visible. This requires that the window is created and has a valid size and that no other QQuickWindow instances are rendering in the same process.
Warning: Calling this function will cause performance problems.
Warning: This function can only be called from the GUI thread.
qml的截屏需要Qt+qml混编。
首先在main.cpp中注册qml中需要用到的类
....setContextProperty("robotData", robotData);
CPP中函数的实现
bool RobotData::screenshot(QQuickWindow *quic)//参数为截屏窗口的ID
{
image=quic->grabWindow();//截屏
QMatrix matrix;
matrix.rotate(270);
image=image.transformed(matrix);//因为设备是竖屏,但截出来的图片是横向显示的,这样看起来很难受,所以先进行一下图片旋转。
QString str="Screenshot";
image.save(str, "PNG");//将截屏保存为PNG图片,命名为“Screenshot.png”。
return true;
}
接下来写qml
ApplicationWindow {
id:root
..{
if(robotData.screenshot(root)){console.log("OK");}//只需在需要的地方加入调用就可以了,root为要截屏窗口的ID。
}
}
以上就完成了,qml窗口的截屏,简单实用。