Convert QImage to QObject
Unsolved
General and Desktop
-
I want to draw the qimage on the canvas through the qwebchannel.
In order to pass qimage to js, I need to convert QImage to QObject.
But the following function throws an error and I don't know why.
How to safely convert QImage to QObject?public slots: QObject * getImgObject(); .... QObject *WPubManager::getImgObject() { // convert QImage to QObject and return value if(m_pBkgnd){ QByteArray byteArray; QBuffer buffer(&byteArray); buffer.open(QIODevice::WriteOnly); // func getBkgndImg return QImage m_pBkgnd->getBkgndImg().save(&buffer, "WEBP"); QJsonObject imageObject; imageObject["data"] = QString::fromLatin1(byteArray.toBase64().data()); imgObject->setProperty("image", QVariant::fromValue(imageObject)); }else{ qDebug() << "no Bkgnd"; } return imgObject; }
// canvas.html
var wpubManager; if (typeof QWebChannel !== 'undefined') { new QWebChannel(qt.webChannelTransport, function (channel) { wpubManager = channel.objects.wpubManager; console.error('wpubManager:', wpubManager); }); } else { console.error("QWebChannel is not defined. Make sure qwebchannel.js is properly loaded."); } var imageData; function drawCanvas(){ **var imageObject = wpubManager.getImgObject();** var base64Image = imageObject.image.data; var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); var img = new Image(); img.src = "data:image/webp;base64," + base64Image; img.onload = function() { context.drawImage(img, 0, 0); }; }
-
@MyNameIsQt said in Convert QImage to QObject:
But the following function throws an error and I don't know why.
It may have been helpful to post the actual error message.
How to safely convert QImage to QObject?
You don't. It should be something like this:
- From C++, register a WPubManager object with your QWebChannel object.
- From JS, access a property of that WPubManager object containing your Base64 encoded image.
-
@ChrisW67
thank you
I couldn't put the following code together. This is my fault.void WpubEditor::on_Open_wpub_triggered() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open wpub file"), "", tr("wpub Files (*.wPub)")); if (!fileName.isEmpty()) { if (!m_pPubManager) { QString htmlPath = QFileInfo(__FILE__).dir().absolutePath() + "/canvas.html"; QFile file(htmlPath); if (file.exists()) { webView->load(QUrl::fromLocalFile(htmlPath)); } else { qDebug() << "Failed to load canvas.html. File not found."; } m_pPubManager = new WPubManager(this, nullptr); channel->registerObject("wpubManager", m_pPubManager); } if (m_pPubManager->OpenWPub(fileName)){ updateStatusBar(fileName); setMenuActionStatus(true); } else { qWarning("Couldn't open file."); } } }