progro
progro

Reputation: 33

Expand cursor length QLineEdit?

I'd like to take a normal QLineEdit, and change the shape of the cursor. So with a subclass like so:

class myLineEdit : public QLineEdit
{
    Q_OBJECT
signals:

public:
    explicit myLineEdit(QWidget * parent = 0)
    {

    }

protected:

};

And make it so that the cursor is several pixels wide, like that of a Linux terminal. By default, the cursor to indicate text position is very slim.

I assume I need to override something in the paintevent()? What exactly in the paintevent would be responsible for drawing the single pixel blinking line QLineEdit() defaults to? I could not find this information in the documentation.

Upvotes: 3

Views: 644

Answers (1)

eyllanesc
eyllanesc

Reputation: 244252

Use a Qproxystyle:

#include <QtWidgets>

class LineEditStyle: public QProxyStyle
{
    Q_OBJECT
    Q_PROPERTY(int cursorWidth READ cursorWidth WRITE setCursorWidth)
public:
    using QProxyStyle::QProxyStyle;
    int cursorWidth() const{
        if(m_cursor_width < 0)
            return baseStyle()->pixelMetric(PM_TextCursorWidth);
        return pixelMetric(PM_TextCursorWidth);
    }
    void setCursorWidth(int cursorWidth){
        m_cursor_width = cursorWidth;
    }
    int pixelMetric(QStyle::PixelMetric metric, const QStyleOption *option = nullptr, const QWidget *widget = nullptr) const override
    {
        if(metric == PM_TextCursorWidth)
            if(m_cursor_width > 0)
                return  m_cursor_width;
        return  QProxyStyle::pixelMetric(metric, option, widget);
    }
private:
    int m_cursor_width = -1;
};

class LineEdit: public QLineEdit
{
    Q_OBJECT
public:
    LineEdit(QWidget *parent = nullptr):
        QLineEdit(parent)
    {
        LineEditStyle *new_style = new LineEditStyle(style());
        new_style->setCursorWidth(10);
        setStyle(new_style);
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    LineEdit w;
    w.show();
    return a.exec();
}
#include "main.moc"

enter image description here

Upvotes: 1

Related Questions