Domanda

I would like to open a window when I click on a QSpinBox. The problem is that there is no such signal "clicked" for this widget.

Does someone has an idea how to do that?

È stato utile?

Soluzione

A QSpinBox is just a QLineEdit with two buttons, input validation and event handling. It doesn't have clicked signal because it's supposed to handle the mouse even itself.

The problem is that even making a custom widget derived from QSpinBox won't be enough since it doesn't receive the mouse events itself, they are handled by its children widgets. You could install an event filter on the QSpinBox children in order to catch the click event, but that's not the neatest way.

If you just want to display a numpad when the user select the box, you can use directly a QLineEdit. You will lose the QSpinBox buttons (but you can add your own ones if you need them) and the validation (but you can add you own using QValidator).

Then you just have to derive it in order to catch the focus event, trigger a custom signal which would show your keyboard :

class MySpinBox: public QLineEdit
{
  Q_OBJECT

public:
  MySpinBox(QWidget *parent = 0);
  ~MySpinBox();

signals:
  needNumpad(bool hasFocus);

protected:
  virtual void focusInEvent(QFocusEvent *e) {
      QLineEdit::focusInEvent(e);
      emit(needNumpad(true));
  }
  virtual void focusOutEvent(QFocusEvent *e) {
      QLineEdit::focusInEvent(e);
      emit(needNumpad(false));
  }
}

Altri suggerimenti

You can use an event filter and do something like this:

ui->spinBox->installEventFilter(this);
QObjectList o_list = ui->spinBox->children();
for(int i = 0; i < o_list.length(); i++)
{
    QLineEdit *cast = qobject_cast<QLineEdit*>(o_list[i]);
    if(cast)
        cast->installEventFilter(this);
}

And in the event filter you check for a mouse click (in this example its triggered by all mouse buttons, left click, right click, scroll wheel click etc.).

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    if(event->type() == QEvent::MouseButtonPress)
    {
        showNumpadDialog();
    }
    return false;
}

You do not need to create your own QSpinBox with QLineEdit and two buttons.

Since QLineEdit is the child of QSpinBox. You can create an event filter for QLineEdit and check whether its parent is a spinbox. Then so, you would get a click event for spin box.

   if(event->type() == QEvent::MouseButtonPress && dynamic_cast<QSpinBox *>(dynamic_cast<QLineEdit *>(obj)->parent()) )
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top