Bernard
Bernard

Reputation: 4600

How to have button as signal and table as slot in Qt?

I know the very basic of Qt. The only thing I need is a button and a table. When the user presses the button, I fill the table in with data which comes from database. I have already figured out the database part, mostly.


Now my main problem is Qt signals and slots. In Java, we do it by events and handlers. How can I connect my button to an update of the table. Or if it is better, I could update the table when programs run.

Any sample code or reference where I can find the right direction would be appreciated!

Upvotes: 1

Views: 406

Answers (1)

László Papp
László Papp

Reputation: 53235

This is very ismple. You would use Qt signal slot mechanism for this. You need to connect the button's clicked signal to your update handler slot for the database.

#include <QObject>
#include <QPushButton>

...

class UpdateHandler : public QObject
{
    Q_OBJECT
    public:
    explicit UpdateHandler(QObject *parent) : QObject(parent)
    {
        connect(&m_pushButton, SIGNAL(clicked(bool)), SLOT(updateDatabase()));
    }

    public slots:
    void updateDatabase()
    {
        // update the database here.
    }
    private:
        QPushButton m_pushButton;
};

With C++11 support, this would be even simpler as you could use lambda.

    UpdateHandler::UpdateHandler(QObject *parent) : QObject(parent)
    {
        connect(&m_pushButton , &QPushButton::clicked,  [&] {
            // update the database here
        }};
    }

Disclaimer: this is just proto type code, so this was not even compilation-tested, but it should get you going, I think.

Here is a good example how to create signals and slots using QtCreator:

Creating a Qt Widget Based Application

enter image description here

Here you can find the all Qt 4.8 documentation for that if you still happen to use that:

Qt Designer's Signals and Slots Editing Mode

enter image description here

Upvotes: 2

Related Questions