Qt custom QPushButton clicked signal

让人想犯罪 __ 提交于 2019-12-13 00:53:56

问题


I want to send two integers, string and fret, to a SLOT that will process the location of the button that was pressed. The SIGNAL and SLOT argument have to match so I am thinking I need to reimplement the QPushButton::clicked event method. Problem is I am new to Qt and could use some direction.

connect(&fretBoardButton[string][fret], SIGNAL(clicked()), this, SLOT     (testSlot()));

回答1:


If you use the C++11 connection syntax you can use a lambda with calls testSlot with your string and fret arguments:

connect(&fretBoard[string][fret], &QPushButton::clicked, [this, string, fret]() {
    testSlot(string, fret);
});

This code creates a lambda using the [captures, ...](arguments, ...) { code } syntax. When you make the connection it captures the string and fret variable values, and will then pass them on to testSlot when the button is clicked.




回答2:


There are Two approaches you could use to add the string and fret information. one is to use the sender() function to get the button which emitted the signal. you can the access fret and string if they are members of your button class so in the SLOT you would have.

MyPushButton *button = (MyPushButton *)sender();
button.getFret();
button.getString(); 

However since you are already subClassing QPushButton you could use a private SLOT to catch the buttonClicked signal and re-emit a signal with the right values.

In the constructor

connect(this, SIGNAL(clicked()), this, SLOT(reemitClicked()));

and then the reemit SLOT

void MyPushButton::reemitClicked()
{
    emit clicked(m_fret, m_string);
}

be sure to add the appropriate private slot and public signal to you class https://doc.qt.io/archives/qq/qq10-signalmapper.html see this artical for a good discussion on various ways to add an argument to signal.



来源:https://stackoverflow.com/questions/34668541/qt-custom-qpushbutton-clicked-signal

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