QLabel click event using Qt?

后端 未结 3 1121
无人共我
无人共我 2021-01-12 11:01

I\'m new in Qt and have a question.

I have QLabel and QLineEdit objects, and when QLabel text is clicked on, I want to set thi

3条回答
  •  青春惊慌失措
    2021-01-12 11:22

    A simple way to accomplish that, without a need for any subclassing, is a signal source that monitors the events on some object and emits relevant signals:

    // main.cpp - this is a single-file example
    #include 
    
    class MouseButtonSignaler : public QObject {
      Q_OBJECT
      bool eventFilter(QObject * obj, QEvent * ev) Q_DECL_OVERRIDE {
        if ((ev->type() == QEvent::MouseButtonPress
            || ev->type() == QEvent::MouseButtonRelease
            || ev->type() == QEvent::MouseButtonDblClick)
            && obj->isWidgetType())
          emit mouseButtonEvent(static_cast(obj), 
                                static_cast(ev));
        return false;
      }
    public:
      Q_SIGNAL void mouseButtonEvent(QWidget *, QMouseEvent *);
      MouseButtonSignaler(QObject * parent = 0) : QObject(parent) {}
      void installOn(QWidget * widget) {
        widget->installEventFilter(this);
      }
    };
    

    The emit keyword is an empty macro, Qt defines it as follows:

    #define emit
    

    It is for use by humans as a documentation aid prefix only, the compiler and moc ignore it. As a documentation aid, it means: the following method call is a signal emission. The signals are simply methods whose implementation is generated for you by moc - that's why we have to #include "main.moc" below to include all the implementations that moc has generated for the object class(es) in this file. There's otherwise nothing special or magical to a signal. In this example, you could look in the build folder for a file called main.moc and see the implementation (definition) of void MouseButtonSignaler::mouseButtonEvent( .. ).

    You can then install such a signaler on any number of widgets, such as a QLabel:

    int main(int argc, char ** argv) {
      QApplication app(argc, argv);
      MouseButtonSignaler signaler;
      QWidget w;
      QVBoxLayout layout(&w);
      QLabel label("text");
      QLineEdit edit;
      layout.addWidget(&label);
      layout.addWidget(&edit);
      signaler.installOn(&label);
      QObject::connect(&signaler, &MouseButtonSignaler::mouseButtonEvent, 
        [&label, &edit](QWidget*, QMouseEvent * event) {
        if (event->type() == QEvent::MouseButtonPress)
          edit.setText(label.text());
      });
      w.show();
      return app.exec();
    }
    
    #include "main.moc"
    

提交回复
热议问题