1

我有 2 节课,第一节课有 QPushButton,第二节课有 QLabel(我把它放在“public”上)。我想当用户单击第一类中的按钮时,第二类中的 QLabel 会更改文本。我想我应该写一个函数来做到这一点,当用户点击按钮时,按钮会调用这个函数,这就是我的函数(在我看来):

void A::buttonClicked(B *bClass)
{
    bClass->label->setText("Button was clicked!");
}

这就是我在头等舱按按钮调用它的方式:

connect(button, SIGNAL(clicked()), this, SLOT(buttonClicked(B)));

但是我不知道为什么当我点击时,第二类上的标签没有改变。我该怎么做?对不起我的英语

4

2 回答 2

2

您的代码的问题是您试图将没有参数的信号连接到需要一个参数的插槽:

connect(button, SIGNAL(clicked()), this, SLOT(buttonClicked(B)));

当你运行你的应用程序时,你可能会收到一条消息,上面写着QObject::connect: Incompatible sender/receiver arguments. 所以那行不通。

为了解决这个问题,你可以在类B中添加一个函数来改变它的文本QLabel

void B::changeLabelText(const QString &text)
{
   label->setText(text);
}

然后在 class 中有一个插槽A,调用 class 中的changeLabelText(const QString &text)函数B,并将其连接到按钮的 clicked 信号:

   objectB = new B;
   connect(button, SIGNAL(clicked()), this, SLOT(clickedSlot()));
   ...    

void A::clickedSlot()
{
   objectB->changeLabelText("Button clicked");
}

请记住将其声明为以下位置的插槽A.h

public slots:
    void clickedSlot();
于 2013-08-09T06:25:00.873 回答
1

This will help you have to make two connections

connect(button, SIGNAL(clicked()), this, SLOT(buttonClicked());
connect(button, SIGNAL(clickedSomeButton(B)), this, SLOT(buttonClicked(B)));

In the slot buttonClicked() do this

void buttonClicked(){

   emit clickedSomeButton(B);

}

While using signal and slots you have to keep in mind that a slot can have arguments equal or lesser than the signal it is connected to because of this reason your code is not working.

What you need to do is to create a slot for the clicked action of button one . Then in the slot you again emit one signal with the argument B ( This signal you need to define yourself ) which can be caught by the slot you mentioned i.e., buttonClicked(B)

For creating signal use this syntax

 signals:
    double clickedSomeButton(B &)
于 2013-08-08T15:40:25.863 回答