0
for(i=0; i<height; i++)
{
    for(j=0; j<width; j++)
    {
        button[i][j] = new QPushButton("Empty", this);
        button[i][j]->resize(40, 40);
        button[i][j]->move(40*j, 40*i);
        connect(button[i][j], SIGNAL(clicked()), this, SLOT(changeText(button[i][j])));
    }
}

関数 changeText を関数 (fullScreen など) で変更すると機能しますが、自分で定義したスロット (changeText) を使用すると、このエラーが表示され、解決方法がわかりません

QObject::connect: No such slot buttons::changeText(&button[i][j])

これは関数 changeText です。

void buttons::changeText(QPushButton* button)
{
    button->setText("Fish");
}

注:ヘッダーファイルで、次のようにスロットを定義しました:

クラス ボタン : public QWidget

    Q_OBJECT
public slots:
    void changeText(QPushButton* button);
4

3 に答える 3

5
  1. スロットは、シグナルよりも少ない引数を持つことができますが、スロットが持つ引数のタイプは、接続されたシグナルの引数のタイプと正確に一致する必要があります。
  2. そのような動的スロットを持つことはできません。
  3. おそらく必要なのはQSignalMapperです。

ここにサンプルがあります:

QSignalMapper *map = new QSignalMapper(this);
connect (map, SIGNAL(mapped(QString)), this, SLOT(changeText(QString)));
for(i=0; i<height; i++)
{
    for(j=0; j<width; j++)
    {
        button[i][j] = new QPushButton("Empty", this);
        button[i][j]->resize(40, 40);
        button[i][j]->move(40*j, 40*i);
        connect(button[i][j], SIGNAL(clicked()), map, SLOT(map()));
        map->setMapping(button[i][j], QString("Something%1%2").arg(i).arg(j));
    }
}

おそらく、テーブルを削除できます。

于 2013-06-16T22:13:00.750 に答える
1

QButtonGroup is a class that has been designed as a handy collection for buttons. It give you direct access to the button which triggered the slot. It also provide you the possibility to register button with a given id. This can be useful if you want to retrieve easily some meta information from the button id.

QButtonGroup* buttongrp = new QButtonGroup();

for(i=0; i<height; i++)
{
    for(j=0; j<width; j++)
    {
        button[i][j] = new QPushButton("Empty", this);
        button[i][j]->resize(40, 40);
        button[i][j]->move(40*j, 40*i);
        buttongrp->addButton(button[i][j], i << 16 + j);
    }
}

QObject::connect(buttongrp, SIGNAL(buttonClicked(int)), 
                      this, SLOT(getCoordinates(int)));
QObject::connect(buttongrp, SIGNAL(buttonClicked(QAbstractButton  *)),
                   this, SLOT(changeText(QAbstractButton  * button)));

...

void MyObject::changeText(QAbstractButton * button)
{
    button->setText("Fish");
}

void MyObject::getCoordinates(int id){
  int i = id >> 16;
  int j = ~(i << 16) & id;
  //use i and j. really handy if your buttons are inside a table widget
}

Usually you don't need to connect to both slots. For the id I assumed that height and width are less that 2^16.

Retrospectively, It seems to me you are reimplementing some of the functions of the button group.

于 2013-06-17T08:25:35.337 に答える