Signal click on QSpinBox Qt

拜拜、爱过 提交于 2020-07-07 11:46:54

问题


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?


回答1:


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));
  }
}



回答2:


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;
}



回答3:


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()) )


来源:https://stackoverflow.com/questions/16294975/signal-click-on-qspinbox-qt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!