Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Make QGraphicsTextItem show the cursor being moved



  • I am trying to make a QGraphicsTextItem that has constant width, follow its cursor when the latter moves.

    @
    #include <QtGui/QCursor>
    #include <QtGui/QTextCursor>
    #include <QtGui/QTextDocument>
    #include <QtGui/QGraphicsTextItem>

    class GraphicsTextEditor : public QGraphicsTextItem
    {
    Q_OBJECT
    public:
    GraphicsTextEditor(QGraphicsItem *parent = 0)
    : QGraphicsTextItem( parent )
    {
    this->init();
    }

    GraphicsTextEditor(const QString &text, QGraphicsItem *parent = 0)
        : QGraphicsTextItem( text, parent )
    {
        this->init();
    }
    
    virtual QRectF boundingRect() const
    {
        static const int FIXED_WIDTH = 100;
        const QRectF bounds = QGraphicsTextItem::boundingRect();
        return QRect( bounds.left(), bounds.top(), FIXED_WIDTH, bounds.height() );
    }
    

    private slots:
    void onTextCursorPositionChanged(const QTextCursor &textCursor)
    {
    QCursor c = this->cursor();
    c.setPos( textCursor.position(), c.pos().y() );
    this->setCursor( c );
    }

    private:
    void init()
    {
    this->setTextInteractionFlags( Qt::TextEditorInteraction );
    connect( this->document(),
    SIGNAL(cursorPositionChanged(QTextCursor)),
    SLOT(onTextCursorPositionChanged(QTextCursor)));
    }
    };
    @

    I don't want to achieve the behavior of QGraphicsTextItem::setTextWidth - I want the QGraphicsTextItem to be single-line text editor that scrolls its text to the position of its cursor (the visual one) when the cursor moves. Moving the cursor in edit mode doesn't change the QGraphicsTextItem::textCursor's position - only the QGraphicsItem::cursor's one. Setting the QGraphicsItem::cursor's position doesn't make QGraphicsTextItem show the text which the cursor points at.


Log in to reply