Expand cursor length QLineEdit?

后端 未结 1 529
独厮守ぢ
独厮守ぢ 2021-01-23 06:05

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_OB         


        
相关标签:
1条回答
  • 2021-01-23 07:06

    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"
    

    0 讨论(0)
提交回复
热议问题