Change QLineEdit text cursor shape



  • Hi All,

    Is there any way to change the blinking text cursor shape in
    a QLineEdit widget? Such as, to change the shape of the cursor
    from thin vertical line to a block style.

    Thanks

    Brisco



  • Well, you can customize QStyle in order to return a different cursor size for QStyle::PM_TextCursorWidth

    Example for a 10-pixel large cursor ( just an idea, it's not written in a clean way :) ):

    class LineEditStyle : public QCommonStyle
    {
    public:
      int pixelMetric(PixelMetric metric, const QStyleOption *option = 0, const QWidget *widget = 0) const;
    };
    
    class LineEdit : public QLineEdit
    {
        Q_OBJECT
    
    public:
        LineEdit(QWidget *parent = 0);
    };
    
    int LineEditStyle::pixelMetric(PixelMetric metric, const QStyleOption *option, const QWidget *widget) const
    {
      if (metric == QStyle::PM_TextCursorWidth)
        return 10;
    
      return QCommonStyle::pixelMetric(metric,option,widget);
    }
    
    LineEdit::LineEdit(QWidget *parent)
        : QLineEdit(parent)
    {
      setStyle(new LineEditStyle);
    }
    

    Allocate a LineEdit and it should work :) AFAIK, you can change the width, but I haven't found any other properties.

    Antonio.



  • Hey, I didn't know that there's QProxyStyle class, that lets you implement the above solution in a better way :)

    class LineEditStyle : public QProxyStyle
    {
    public:
      LineEditStyle(QStyle *style = 0) : QProxyStyle(style) { }
    
      int pixelMetric(PixelMetric metric, const QStyleOption *option = 0, const QWidget *widget = 0) const;
    };
    
    class LineEdit : public QLineEdit
    {
      Q_OBJECT
    
    public:
      LineEdit(QWidget *parent = 0);
    };
    
    int LineEditStyle::pixelMetric(PixelMetric metric, const QStyleOption *option, const QWidget *widget) const
    {
      if (metric == QStyle::PM_TextCursorWidth)
        return 10;
    
      return QProxyStyle::pixelMetric(metric,option,widget);
    }
    
    LineEdit::LineEdit(QWidget *parent)
        : QLineEdit(parent)
    {
      setStyle(new LineEditStyle(style()));
    }
    

    So it will adapt perfectly to your default style for QLineEdit.



  • Antonio,

    It works.

    Thanks for your helpful reply.



  • Why I can't apply this solution on a QTextEdit's cursor?


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.