开发者

Qt Button Handling Advice

I have come to the point where I am tired of how I am handling user input in Qt (namely QPushButton presses) and I am looking for advice on the best method in which to handle these events.

Below is an example of what I am currently doing:

MyClass.h

class MyClass : public QMainWindow
{
    Q_OBJECT

public:

    ...

    QPushButton* getButtonA( );
    QPushButton* getButtonB( );

public slots:

    void buttonAPressed( );
    void buttonBPressed( );

private:

    ...

};

main.cpp

int main( int argc, char* argv[ ] )
{
    QApplication a( argc, argv );
    MyClass w;

    w.show( );

    QObject::connect( w.getButtonA( ), SIGNAL( clicked( ) ), &w, SLOT( b开发者_Python百科uttonAPressed( ) ) );
    QObject::connect( w.getButtonB( ), SIGNAL( clicked( ) ), &w, SLOT ( buttonBPressed( ) ) );

    return a.exec( );
}

It works fine but I just feel that there must be a better/more elegant way than this, right?


I'm guessing that you are designing the UI with Designer. Suppose you have a button named pushButtonStart for your MyClass class. Then you can place the connections inside MyClass's constructor as Matt Rogers states:

MyClass::MyClass()
{
    connect(ui->pushButtonStart, SIGNAL(clicked()), this, SLOT(startPressed());
}

However, you can further simplify this technique of handling slots for signals emitted from UI controls. The above connect() call is not required if you define a function with the following specific way:

MyClass.h

MyClass
{
...

public slots:
    void on_pushButtonStart_clicked();

...
};

MyClass.cpp

MyClass::on_pushButtonStart_clicked()
{
    // code goes for pushButtonStart's clicked signal
}

The name of the function has to be very specific:

  1. It must start with on_.
  2. Then there should be the name of the control: pushButtonStart.
  3. There there should be an underscore followed by the name of the signal: _clicked.

Qt magic. Qt automatically connect pushButtonStart's clicked signal with on_pushButtonStart_clicked slot. You don't need to specify the connection separately.


You are actually using the standard way of handling button presses in Qt. The only other way that I'm aware of is by having MyClass be an event filter for the buttons, that seems like overkill in this case.

The only change I would make to your code is to put the signal -> slot connections in MyClass itself. In this example, I'll assume that you want to set them up in the constructor, which would look like this:

MyClass::MyClass()
{
    QObject::connect( w.getButtonA( ), SIGNAL( clicked( ) ), &w, SLOT( buttonAPressed( ) ) );
    QObject::connect( w.getButtonB( ), SIGNAL( clicked( ) ), &w, SLOT( buttonBPressed( ) ) );
}

This keeps the connections out of the main method and groups them where they should be, which is in the class that contains the buttons that emit the signals.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜