Search code examples
c++qtqdoublespinbox

How to mark the whole text by double clicking for QDoubleSpinBox?


I have a class which inherit from QDoubleSpinBox.

 class NumericEdit : public QDoubleSpinBox
 {      
 public:
   NumericEdit( QWidget *p_parent = nullptr );

 protected:
   bool event( QEvent *p_event ) override;
   void keyPressEvent( QKeyEvent *p_event ) override;
   void keyReleaseEvent( QKeyEvent *p_event ) override;
   void focusInEvent( QFocusEvent *p_event ) override;
   void focusOutEvent( QFocusEvent *p_event ) override;
   ............
 };

 NumericEdit::NumericEdit( QWidget *p_parent ) : QDoubleSpinBox( p_parent )
 {
   initStyleSheet();
   setButtonSymbols( QAbstractSpinBox::NoButtons );
   setGroupSeparatorShown( true );
   ..........
 }

The result when I double click into the editing field is like this, only the part in between group separators is marked. If I triple click, the whole text is then marked.

enter image description here

How should I change, sothat when I double click into the editing field (no matter in integer part or decimal part), the whole text is marked?

enter image description here


Solution

  • Solution is reimplementing of QLineEdit::mouseDoubleClickEvent method (not QDoubleSpinBox::mouseDoubleClickEvent).

    Custom line edit:

    class ExtendedLineEdit : public QLineEdit
    {
        Q_OBJECT
    public:
        explicit ExtendedLineEdit(QWidget *parent = nullptr);
    protected:
        void mouseDoubleClickEvent(QMouseEvent *event);
    }
    
    void ExtendedLineEdit::mouseDoubleClickEvent(QMouseEvent *event)
    {
        if (event->button() == Qt::LeftButton)
        {
            selectAll();
            event->accept();
            return;
        }
    
        QLineEdit::mouseDoubleClickEvent(event);
    }
    

    And then set it to your custom spin box

    NumericEdit::NumericEdit(QWidget *p_parent) : QDoubleSpinBox(p_parent)
    {
        //...
        ExtendedLineEdit* lineEdit = new ExtendedLineEdit(this);
        setLineEdit(lineEdit);
    }