【发布时间】:2014-03-20 15:50:20
【问题描述】:
我有一个自定义小部件,我想将它添加到 QTextEdit(通过拖放),然后允许用户双击小部件以打开单独的编辑窗口。
现在我将它拖到可以将小部件拖到 QTextEdit 上的位置,并添加了一个图像来表示文档中的小部件。这是通过实现 QTextObjectInterface 的包装类完成的。
现在我需要弄清楚如何处理鼠标事件,以便当用户单击图像时,程序知道会调出自定义编辑 GUI。
我现在拥有的大概是,
class MyWidget : public QWidget
{ ... }
class MyWidgetWrapper : public QObject, QTextObjectInterface
{
Q_OBJECT
Q_INTERFACES(QTextObjectInterface)
....
void drawObject(QPainter *painter, const QRectF &rect, QTextDocument *doc, int posInDocument, const QTextFormat &format)
{
MyWidgetWrapper *tmp = qvariant_cast<MyWidgetWrapper*>(format.property(1));
painter->drawImage(rect, tmp->mMyWidget.getImage());
}
private:
MyWidget mMyWidget;
}
然后,在我的自定义 QTextEdit 类中,我有
bool MyTextEdit::initialize()
{
MyWidgetWrapper *tmp = new MyWidgetWrapper();
document()->documentLayout()->registerHandler(MyWidgetWrapperFormat, tmp);
return true;
}
void MyTextEdit::insertFromMimeData(const QMimeData *source)
{
if(source->hasFormat("application/x-MyWidgetWrapper"))
{
MyWidgetWrapper *widgetWrapper = new MyWidgetWrapper(this);
QTextCharFormat charFormat;
charFormat.setObjectType(MyWidgetWrapperFormat);
charFormat.setProperty(MyWidgetWrapperData, QVariant::fromValue(widgetWrapper));
QTextCursor cursor = textCursor();
cursor.insertText(QString(QChar::ObjectReplacementCharacter), charFormat);
setTextCursor(cursor);
}
}
【问题讨论】: