QGraphicsTextItem mouseDoubleClickEvent

时间:2011-02-24 16:44:44

标签: quartz-graphics qgraphicstextitem

我是QT的新人。现在一个问题让我感到困惑。

MainWindow中的代码如下:

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    QGraphicsView *view = new QGraphicsView;
    QGraphicsScene *scene =new QGraphicsScene;
    GraphicsTextItem *item = (GraphicsTextItem*)scene->addText(QString("hello world"));
    item->setPos(100,100);
    scene->addItem(item);
    QGraphicsItem *i = scene->itemAt(120,110);
    view->setScene(scene);
    view->show();
}

类GraphicsTextItem继承QGraphicsTextItem,受保护的方法mousePressDown重新实现如下:

void GraphicsTextItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
    qDebug()<<"mouseDoubleClickEvent happens";
    QGraphicsTextItem::mouseDoubleClickEvent(event);
}

应用程序可以正常工作,但是当我双击GraphicsTextItem对象时,GraphicsTextItem类中的mouseDoubleClickEvent没有任何反应。

期待您的回复!

1 个答案:

答案 0 :(得分:2)

我搜索了我的代码并开发了一个示例,因为我留下了问题,但现在是:

#include <QGraphicsTextItem>

class GraphicsTextItem : public QGraphicsTextItem
{
    Q_OBJECT

public:
    GraphicsTextItem(QGraphicsItem * parent = 0);

protected:
    void mouseDoubleClickEvent ( QGraphicsSceneMouseEvent * event );

};

<强>实现:

#include "graphicstextitem.h"
#include <QDebug>
#include <QGraphicsSceneMouseEvent>

GraphicsTextItem::GraphicsTextItem(QGraphicsItem * parent)
    :QGraphicsTextItem(parent)
{
    setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
}

void GraphicsTextItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
    if (textInteractionFlags() == Qt::NoTextInteraction)
        setTextInteractionFlags(Qt::TextEditorInteraction);
    QGraphicsItem::mouseDoubleClickEvent(event);
}

视图

#include "mainwindow.h"
#include <QtGui>
#include <QtCore>
#include "graphicstextitem.h"

MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent)
{
    QGraphicsScene * scene = new QGraphicsScene();
    QGraphicsView * view = new QGraphicsView();
    view->setScene(scene);

    GraphicsTextItem * text = new GraphicsTextItem();
    text->setPlainText("Hello world");
    scene->addItem(text);


    text->setPos(100,100);
    text->setFlag(QGraphicsItem::ItemIsMovable);
    setCentralWidget(view);
}

在此示例中,您可以通过doubleclick与QGraphicsTextItem进行交互并更改文本。我希望你会有所帮助。