2013-05-06 66 views
1

在下面的代码中,我试图用“新文本”替换“原文”,当点击按钮被按下时。我没有得到任何错误,但标签的文字不会改变。QPushbutton没有连接

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

该方法是错误的,我建议你重读文档。简而言之,在连接期间不能指定像“word”这样的实例。 – 2013-05-06 16:06:09

+0

我试过这个,而不是QPushButton :: connect(button,SIGNAL(clicked()),layout,SLOT(setText(“new text”))); – g3nair 2013-05-06 16:07:58

+0

也没有工作! – g3nair 2013-05-06 16:08:27

回答

3

主要这里的一点是,信号和槽的签名应该是兼容。换句话说,仅仅因为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方法。

我鼓励你重新读取文档进行排序的感觉,为什么上面介绍的方法是有效的,而你不是,绝不可能。

+0

非常感谢!我现在正在再次阅读文档,并慢慢清楚为什么我的代码不起作用。是的,我的意思是使用标签。再次感谢。 – g3nair 2013-05-06 17:04:28