qtextbrowser获取_QTextBrowser – 如何从鼠标点击位置识别图像

documentation:

Inline images are represented by an object replacement character (0xFFFC in Unicode) which has an associated QTextImageFormat. The image format specifies a name with setName() that is used to locate the image.

您可以在光标上使用charFormat().toImageFormat().name()来提取图像的URL.以下是一个独立的示例.有两个值得注意的细节:

>光标有时会指向图像之前的一个字符.因此,解决方法; Qt 4.8.5和5.1.1似乎都是必要的.

>弹出菜单应异步显示,以免阻止应用程序的其余部分.文档中提供的示例代码是糟糕用户体验的来源,应被视为邪恶的憎恶.所有小部件都可以在关闭时自动删除,因此菜单不会泄漏. QPointer仅用于证明这一事实.它跟踪菜单的生命周期,并在菜单删除时自动为空.

#include

#include

#include

#include

#include

#include

#include

#include

#include

class Browser : public QTextBrowser

{

QPointer m_menu;

protected:

void contextMenuEvent(QContextMenuEvent *ev) {

Q_ASSERT(m_menu.isNull()); // make sure the menus aren't leaking

m_menu = createStandardContextMenu();

QTextCursor cur = cursorForPosition(ev->pos());

QTextCharFormat fmt = cur.charFormat();

qDebug() << "position in block" << cur.positionInBlock()

<< "object type" << cur.charFormat().objectType();

if (fmt.objectType() == QTextFormat::NoObject) {

// workaround, sometimes the cursor will point one object to the left of the image

cur.movePosition(QTextCursor::NextCharacter);

fmt = cur.charFormat();

}

if (fmt.isImageFormat()) {

QTextImageFormat ifmt = fmt.toImageFormat();

m_menu->addAction(QString("Image URL: %1").arg(ifmt.name()));

}

m_menu->move(ev->globalPos());

m_menu->setAttribute(Qt::WA_DeleteOnClose); // the menu won't leak

m_menu->show(); // show the menu asynchronously so as not to block the application

}

};

void addImage(QTextDocument * doc, const QString & url) {

QImage img(100, 100, QImage::Format_ARGB32_Premultiplied);

img.fill(Qt::white);

QPainter p(&img);

p.drawRect(0, 0, 99, 99);

p.drawText(img.rect(), url);

doc->addResource(QTextDocument::ImageResource, QUrl(url), img);

}

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

{

QApplication a(argc, argv);

QTextDocument doc;

Browser browser;

doc.setHtml("");

addImage(&doc, "data://image1");

addImage(&doc, "data://image2");

browser.show();

browser.setDocument(&doc);

return a.exec();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值