Qt - 自定义信号发送整数 [英] Qt - custom signal sending an integer
问题描述
我有一系列自定义按钮。我想创建一个自定义信号,当连接到一个以整数作为参数的插槽时,会向它发送一个变量。
所以,例如,假设我有10个按钮,每个按钮都有一个从0到9的id。我将它们全部连接到一个函数,它接受一个整数参数。该函数在被调用时会打印出它的参数。现在,当我按下按钮4时,我想看到我的屏幕上印有4个。
我以前从未创建过自定义信号,所以我会非常感谢任何帮助。
我尝试过:
我还没有尝试过任何东西。我只创建了这个类。
I have an array of custom buttons. I want to create a custom signal, which, when connected to a slot, which takes an integer as an argument, will send a variable to it.
So for example, let's say I've got 10 buttons, each of them has an id from 0 to 9. I connect all of them to a single function, which takes an integer argument. The function, when called, prints it's argument. Now when I press button 4, I want to see a 4 printed on my screen.
I've never created a custom signal before, so I'd be very grateful for any help.
What I have tried:
I haven't tried anything yet. I've only created the class.
推荐答案
只需要实现一个QPushButton :: clicked()
插槽连接到多个按钮。在内部sender()
转换为QPushButton *
以访问该按钮并识别它。然后,您可以使用其他参数发出用户定义的信号。
另一种方法是使用C ++ 11 lambda:
Just implement aQPushButton::clicked()
slot that is connected to multiple push buttons. Inside that castsender()
toQPushButton*
to access the button and identify it. You can then emit a user defined signal with additional parameters.
Another method would be using a C++11 lambda:
int counter = 1;
// Create button or access it using the ui member
//QPushButton *button = new QPushButton;
button->setProperty("myId", counter++);
connect(button, &QPushButton::clicked, [this, button](){
qDebug() << button->property("myId").toString();
ui->label->setText(button->text());
});
// Repeat for the other buttons
以上是使用属性系统提供ID,将其打印到调试窗口并为按钮的标题文本设置标签。
The above is using the property system to provide IDs, printing it to the debug window and setting a label to the button's caption text.
这篇关于Qt - 自定义信号发送整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!