【问题标题】:How to get Click Event of QLineEdit in Qt?如何在 Qt 中获取 QLineEdit 的点击事件?
【发布时间】:2011-06-23 09:39:53
【问题描述】:

如何在Qt中获取QLineEdit的点击事件?

我在QLineEdit 中看不到任何与点击相关的 SLOT 吗?

【问题讨论】:

  • 您要求 QLineEdit 上的点击事件的任何实际原因?
  • @emaillenin :是的,我想在单击文本框时带来另一个自定义控件...

标签: qt


【解决方案1】:

我不认为继承 QLineEdit 是正确的选择。如果不需要,为什么要子类化?您可以改为使用事件过滤器。查看QObject::eventFilter

例子:

MyClass::MyClass() :
    edit(new QLineEdit(this))
{
    edit->installEventFilter(this);
}

bool MyClass::eventFilter(QObject* object, QEvent* event)
{
    if(object == edit && event->type() == QEvent::FocusIn) {
        // bring up your custom edit
        return false; // lets the event continue to the edit
    }
    return false;
}

【讨论】:

  • 看起来QEvent::FocusIn 在这里更合适。
  • 没有QEvent::MouseClick 事件。请改用QEvent::MouseButtonPres
【解决方案2】:

您需要在扩展 QLineEdit 的新类中重新实现 focusInEvent。以下链接将为您提供帮助。

  1. http://doc.qt.io/qt-5/qwidget.html#focusInEvent
  2. QLineEdit - focus event
  3. How to know if a QLineEdit got focus?
  4. QLineEdit Focus Event

【讨论】:

    【解决方案3】:

    虽然没有“点击”或“输入”事件。您可以使用

    void cursorPositionChanged(int old, int new)
    

    Signal。当用户单击 lineedit(如果已启用)以及其他一些情况下会发出它,因此您必须验证实际发生了哪些事件,但我认为这仍然比子类化或对某些应用程序使用事件侦听器更容易.

    【讨论】:

      【解决方案4】:

      如果这有帮助,我不知道, 输入文本后,我必须调用一个函数。我就是这样做的。

      connect(ui->passwordSetLineEdit,SIGNAL(textEdited(QString)),this,SLOT(onTextEdit(QString)));
      

      当输入文本时会发出 textEdited 信号,因此我的 onTextEdit 函数将被调用。

      【讨论】:

        【解决方案5】:

        QLineEdit 没有像 clicked() 这样的信号,但您可以将其子类化并在您的 mouseReleaseEvent 的自定义实现中发出此类信号。

        【讨论】:

          【解决方案6】:

          我多次使用这个解决方案

          def clickable(widget): # make this function global
              class Filter(QObject):
                  clicked = pyqtSignal()
          
                  def eventFilter(self, obj, event):
                      if obj == widget and event.type() == QEvent.MouseButtonRelease and obj.rect().contains(event.pos()):
                          self.clicked.emit()
                          return True
                      else:
                          return False
              filter = Filter(widget)
              widget.installEventFilter(filter)
              return filter.clicked
          
          clickable(self.lineedit).connect(self.test) #use this in class
          
          def test(self):
              print("lineedit pressed")
              pass
          

          【讨论】:

          • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
          猜你喜欢
          • 2018-03-22
          • 1970-01-01
          • 1970-01-01
          • 2020-05-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多