简体   繁体   English

Qt自定义QPushButton点击信号

[英]Qt custom QPushButton clicked signal

I want to send two integers, string and fret, to a SLOT that will process the location of the button that was pressed. 我想将两个整数(字符串和品格)发送到SLOT,该SLOT将处理按下的按钮的位置。 The SIGNAL and SLOT argument have to match so I am thinking I need to reimplement the QPushButton::clicked event method. SIGNAL和SLOT参数必须匹配,所以我想我需要重新实现QPushButton :: clicked事件方法。 Problem is I am new to Qt and could use some direction. 问题是我是Qt的新手,可以使用一些指导。

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

If you use the C++11 connection syntax you can use a lambda with calls testSlot with your string and fret arguments: 如果您使用C ++ 11连接语法 ,您可以使用与呼叫拉姆达testSlotstringfret参数:

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

This code creates a lambda using the [captures, ...](arguments, ...) { code } syntax. 此代码使用[captures, ...](arguments, ...) { code }语法创建一个lambda。 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. 当您连接它抓住了stringfret变量的值,然后将它们传递给testSlot按钮被按下时。

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. 一种是使用sender()函数来获取发出信号的按钮。 you can the access fret and string if they are members of your button class so in the SLOT you would have. 如果它们是您的按钮类的成员,则可以使用访问品格和字符串,因此在SLOT中就可以使用。

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. 但是,由于您已经在对QPushButton进行了子类化,因此可以使用私有SLOT来捕获buttonClicked信号并重新发射具有正确值的信号。

In the constructor 在构造函数中

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

and then the reemit SLOT 然后重新放送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://doc.qt.io/archives/qq/qq10-signalmapper.html上看到适当的专用插槽和公共信号,以了解有关在信号上添加参数的各种方法的良好讨论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM