Qt 6.5中ScreenCapture设置window属性报错,是Bug还是操作有误?
问题原因及解决方案
你的问题不是Qt 6.5的Bug,也不是遗漏操作——Qt 6.5的QML版ScreenCapture类确实没有window属性,该属性是从Qt 6.6开始才新增的。你看到的官方文档大概率对应更高版本,因此出现了版本不匹配的问题。
两种解决路径:
1. 升级到Qt 6.6及以上版本
如果允许升级Qt版本,直接升级后,修改代码即可实现指定窗口捕获:
ApplicationWindow { id: root visible: true width: 640 height: 480 MouseArea { id: recording anchors.fill: parent property bool inProcess: false onClicked: { if (recording.inProcess) { screenCapture.active = recording.inProcess = false; recorder.stop(); } else { screenCapture.active = recording.inProcess = true; recorder.record(); } } } CaptureSession { id: captureSession screenCapture: ScreenCapture { id: screenCapture active: false window: root // 升级到Qt6.6+后可正常使用该属性 } recorder: MediaRecorder { id: recorder mediaFormat { fileFormat: MediaFormat.MPEG4 videoCodec: MediaFormat.VideoCodec.H265 } outputLocation: "desired-name.mp4" quality: MediaRecorder.HighQuality } } }
2. 在Qt 6.5中通过C++桥接实现指定窗口捕获
如果无法升级Qt版本,需要通过C++代码将ScreenCapture的窗口设置能力暴露给QML:
步骤1:创建C++辅助类
#include <QObject> #include <QScreenCapture> #include <QWindow> class ScreenCaptureHelper : public QObject { Q_OBJECT public: explicit ScreenCaptureHelper(QObject *parent = nullptr) : QObject(parent) {} Q_INVOKABLE void setCaptureWindow(QScreenCapture *capture, QWindow *window) { if (capture && window) { capture->setWindow(window); } } };
步骤2:在main.cpp中注册类到QML
#include <QGuiApplication> #include <QQmlApplicationEngine> #include "ScreenCaptureHelper.h" int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); qmlRegisterType<ScreenCaptureHelper>("com.example", 1, 0, "ScreenCaptureHelper"); QQmlApplicationEngine engine; const QUrl url(u"qrc:/main.qml"_qs); 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(); }
步骤3:修改QML代码调用辅助类
import QtQuick import QtQuick.Window import QtMultimedia import com.example 1.0 ApplicationWindow { id: root visible: true width: 640 height: 480 ScreenCaptureHelper { id: captureHelper } MouseArea { id: recording anchors.fill: parent property bool inProcess: false onClicked: { if (recording.inProcess) { screenCapture.active = recording.inProcess = false; recorder.stop(); } else { // 通过辅助类设置捕获窗口 captureHelper.setCaptureWindow(screenCapture, root) screenCapture.active = recording.inProcess = true; recorder.record(); } } } CaptureSession { id: captureSession screenCapture: ScreenCapture { id: screenCapture active: false } recorder: MediaRecorder { id: recorder mediaFormat { fileFormat: MediaFormat.MPEG4 videoCodec: MediaFormat.VideoCodec.H265 } outputLocation: "desired-name.mp4" quality: MediaRecorder.HighQuality } } }
内容的提问来源于stack exchange,提问作者excommunicado
相关产品推荐
相关产品推荐

