qt如何知道一个按钮被点击? [英] qt how to know that a pushbutton is clicked?
问题描述
我试图做一个程序,使一些操作与声音。我的问题是,我有3播放按钮和3标签。我想要的,无论我单击播放按钮,声音的名称是在按钮附近的标签应该播放。
我有一个播放插槽没有任何参数。那么,我如何分别连接到每个播放按钮与每个标签?其实,我可以写3个不同的播放功能,但由于我有一些其他功能,它会太长和混乱。
I'm trying to do a program which makes some operations with sounds. My question is that I have 3 Play pushbutton and 3 label. I want that whichever I click on the Play button, the sound whose name is in the label that is near the pushbutton should play. I have a play slot without any parameter. So, how can I connect to every play button with every label respectively? Actually, I can write 3 different play function, but since I have some other functions, it will be too long and confusing. Also, I need 3 play button because I want to play 3 sounds simultaneously.
推荐答案
例如,通过连接 发出所有按钮到插槽的信号,然后使用 QObject :: sender() 找出它是哪个按钮。
For example by connecting the clicked signal from all the buttons to a slot, and then use QObject::sender() to find out which button it was.
让我们假设您的按钮分别命名为 pushButton,pushButton_2 和 pushButton_3 和标签 label,label_2
Let's assume your buttons are named pushButton, pushButton_2 and pushButton_3 and labels label, label_2 and label_3 respectively.
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(play()));
connect(ui->pushButton_2, SIGNAL(clicked()), this, SLOT(play()));
connect(ui->pushButton_3, SIGNAL(clicked()), this, SLOT(play()));
}
void MainWindow::play()
{
QString piece;
QObject* button = QObject::sender();
if (button == ui->pushButton)
{
piece = ui->label->text();
}
else if (button == ui->pushButton_2)
{
piece = ui->label_2->text();
}
else
{
piece = ui->label_3->text();
}
qDebug() << "Starting to play:" << piece;
}
这篇关于qt如何知道一个按钮被点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!