Wiki Wang
Wiki Wang

Reputation: 698

How to make QGraphicsTextItem single line?

I have a QGraphicsTextItem behave as a lineedit, using

setTextInteractionFlags(Qt::TextEditorInteraction);

However it will show multiline if user presses enter. I want it ignore line wraps, how to do that?

Upvotes: 2

Views: 702

Answers (2)

rocambille
rocambille

Reputation: 15996

AFAIK QGraphicsTextItem doesn't implement that functionality. You can do the trick by subclassing QGraphicsTextItem and filter keyboard events:

class MyGraphicsTextItem : public QGraphicsTextItem
{

// ...

protected:

    virtual void keyPressEvent(QKeyEvent* e) override
    {
        if (e->key() != Qt::Key_Return)
        {
            // let parent implementation handle the event
            QGraphicsTextItem::keyPressEvent(e);
        }
        else
        {
            // ignore the event and stop its propagation
            e->accept();
        }
    }
};

Upvotes: 3

Wiki Wang
Wiki Wang

Reputation: 698

I ended up using the following code. Same idea as @wasthishelpful.

class GraphicsLineEditItem : public QGraphicsTextItem {
    Q_OBJECT
public:
    explicit GraphicsLineEditItem(QGraphicsItem *parent = 0) : QGraphicsTextItem(parent)
    { setTextInteractionFlags(Qt::TextEditorInteraction); }

signals:
    void returnPressed();

protected:
    void keyPressEvent(QKeyEvent *event) {
        switch (event->key()) {
        case Qt::Key_Return:
        case Qt::Key_Enter:
            emit returnPressed();
            break;
        default:
            QGraphicsTextItem::keyPressEvent(event);
        }
    }
};

Upvotes: 2

Related Questions