简体   繁体   English

使用JavaScript在QWebView中嵌入图像

[英]Embedding image in QWebView with JavaScript

I am writing a small application with Qt 4.6 (64-bit Arch Linux, though that shouldn't matter) which lets the user edit a document using a QWebView with contentEditable turned on. 我正在用Qt 4.6(64位Arch Linux,尽管没关系)编写一个小型应用程序,该应用程序允许用户使用启用了contentEditable的QWebView来编辑文档。 However, for some reason embedding an image does not work. 但是,由于某种原因,无法嵌入图像。 Here is a code snippet: 这是一个代码片段:

void LeafEditView::onInsertImage()
{
    // bring up a dialog, ask for an image
    QString imagePath = QFileDialog::getOpenFileName(this,tr("Open Image File"),"/",tr("Images (*.png *.xpm *.jpg)"));
    ui->leafEditor->page()->mainFrame()->documentElement().evaluateJavaScript("document.execCommand('insertImage',null,'"+imagePath+"');");
}

The test image does in fact exist and yet absolutely nothing happens. 测试图像实际上确实存在,但绝对没有任何反应。 Bold / italics / underline all work fine via JavaScript, just not images. 粗体/斜体/下划线都可以通过JavaScript正常运行,而不能通过图像正常运行。 Thoughts? 思考?

Check that QWebSettings::AutoLoadImages is enabled. 检查QWebSettings::AutoLoadImages是否已启用。

You could also try: document.execCommand('insertImage',false,'"+imagePath+"'); 您也可以尝试: document.execCommand('insertImage',false,'"+imagePath+"');

Try using relative vs absolute paths to the image. 尝试使用相对路径和绝对路径的图像。

Last but not least, poke around this sample application -- they are using a similar method of Javascript execCommand(), they do some things in a slightly different way such as using QUrl::fromLocalFile . 最后但并非最不重要的一点是,在示例应用程序中QUrl::fromLocalFile -它们使用的是类似Javascript execCommand()的方法,它们以略有不同的方式执行某些操作,例如使用QUrl::fromLocalFile

Best of luck! 祝你好运!

It turns out that WebKit has a policy of not loading resources from the local filesystem without some massaging. 事实证明,WebKit的策略是不进行大量按摩就不会从本地文件系统加载资源。 In my code, I have a WebKit view which I'm using to edit leaves in a notebook. 在我的代码中,我有一个WebKit视图,用于编辑笔记本中的叶子。 The following one-liner solved my issue: 以下一线解决了我的问题:

 ui->leafEditor->page()->mainFrame()->setHtml("<html><head></head><body></body></html>",QUrl("file:///"));

From what I gleaned by lurking around the WebKit mailing list archives, in order to load files from the local filesystem one must set the URI to be file:, and this does the job. 通过浏览WebKit邮件列表档案库,我收集到的信息是,为了从本地文件系统加载文件,必须将URI设置为file:,然后才能完成此工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM