【问题标题】:QPushbutton does not connectQPushbutton 不连接
【发布时间】:2013-05-06 15:59:06
【问题描述】:

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

 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();

【问题讨论】:

  • 方法不对,建议你重读文档。简而言之,你不能在连接过程中指定像word这样的实例。
  • 我试过这个 QPushButton :: connect(button,SIGNAL(clicked()),layout,SLOT(setText("new text")));
  • 当然,这是错误的,请阅读文档。您只是误解了信号和插槽的机制。
  • 我想我做到了。非常感谢!
  • 如果你甚至不检查连接的返回值是否有错误,你怎么能说你没有收到任何错误? -1 表示无法证明的声明。

标签: c++ qt qt4 signals-slots


【解决方案1】:

这里的重点是信号和槽的签名应该兼容。换句话说,您不能仅仅因为setText 具有不同的签名,即接受QString const& 类型的参数,就将信号clicked() 连接到插槽setText(QString const&)

您可以做的是创建一个 "forwarding" 类,该类将定义您的自定义无参数插槽 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 方法。

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

【讨论】:

  • 非常感谢!我现在正在再次阅读文档,并逐渐弄清楚我的代码为什么不起作用。是的,我的意思是使用标签。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 2017-04-01
  • 2017-01-22
  • 1970-01-01
  • 1970-01-01
  • 2013-11-26
相关资源
最近更新 更多