QPushbutton无法连接

时间:2013-05-06 15:59:06

标签: c++ qt qt4 signals-slots

在下面的代码中,当按下“单击”按钮时,我试图用“新文本”替换“原始文本”。我没有收到任何错误,但标签的文字没有变化。

 QPushButton *button=new QPushButton("click");

QLabel *label=new QLabel("original text");
QVBoxLayout *layout=new QVBoxLayout();
QString word("new text");
QWidget *window=new QWidget();

layout->addWidget(button);
layout->addWidget(label);
QPushButton :: connect(button,SIGNAL(clicked()),layout,SLOT(setText(word)));
window->setLayout(layout);
window->show();

1 个答案:

答案 0 :(得分:3)

这里的主要观点是信号和插槽的签名应该兼容。换句话说,您无法将信号clicked()连接到广告符setText(QString const&),因为setText具有不同的签名,即接受QString const&类型的参数。

你可以做的是创建一个“转发”类,它会定义你的自定义无参数插槽setText,以便它可以连接到信号clicked(),例如:

class Forwarder: public QObject {
  Q_OBJECT

public:
  Forwarder(QObject* parent = 0): QObject(parent),
                                  word("new text"),
                                  label(new QLabel("original text")) {
    QPushButton* button = new QPushButton("click");
    QVBoxLayout* layout = new QVBoxLayout();
    QWidget*     window = new QWidget();

    connect(button, SIGNAL(clicked()), this, SLOT(setText()));

    layout->addWidget(button);
    layout->addWidget(label);
    window->setLayout(layout);
    window->show();
  }

protected Q_SLOTS:
  void
  setText() 
  { label->setText(word); }

private:
  QLabel* label
  QString word;
};

请注意您的自定义setText如何与clicked相关联,并且仅将setText次调用转发给label

您的代码中还有两个错误点:

  • 无法在连接期间传递实例,例如:

    ...
    QString word("new text");
    ...
    connect(button, SIGNAL(clicked()), layout, SLOT(setText(word))); // Odd!
    ...
    
  • 您可能想要连接到label而不是layout。 由于您要更改label上的文字,因此您需要致电 setText的{​​{1}}方法,而不是label。此外,layout (作为layout类实例的指针)甚至没有QLayout方法。

我鼓励您重新阅读文档,以便理解为什么上面介绍的方法是有效的方法,而您的方法不是,也可能永远不会。

相关问题