主要这里的一点是,信号和槽的签名应该是兼容。换句话说,仅仅因为setText
具有不同的签名,即接受QString const&
类型的参数,所以不能将信号clicked()
连接到槽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
方法为label
,而不是layout
。此外,layout
(作为指向QLayout
类的实例的指针)甚至没有setText
方法。
我鼓励你重新读取文档进行排序的感觉,为什么上面介绍的方法是有效的,而你不是,绝不可能。
该方法是错误的,我建议你重读文档。简而言之,在连接期间不能指定像“word”这样的实例。 – 2013-05-06 16:06:09
我试过这个,而不是QPushButton :: connect(button,SIGNAL(clicked()),layout,SLOT(setText(“new text”))); – g3nair 2013-05-06 16:07:58
也没有工作! – g3nair 2013-05-06 16:08:27