将按钮连接到任意功能

时间:2013-05-24 05:28:04

标签: c++ qt

我自己试图在Qt中编写程序,将函数连接到Qt5中的按钮。

 #include <QApplication>
 #include <QtGui>
 #include <QPushButton>
 static void insert()
 {
     qDebug() << “pressed”;
 }

 int main(int argc,char *argv[])
 {
     QApplication app(argc,argv);
     QPushButton *button=new QPushButton(“button”);
     button->setGeometry(50,100,150,80);
     QObject::connect(button,&QPushButton::clicked,insert());
     button->show();
  }

但我得到的错误就像     main.cc:23:39:错误:在此上下文中     main.cc:23:55:错误:无效使用void表达式     make: * [main.o]错误1

请帮忙......

2 个答案:

答案 0 :(得分:8)

在Qt 5中,您需要使用新的qt signal and slots system。连接看起来像:

QObject::connect(button,&QPushButton::clicked,insert); <-- no parentheses.

已经说明了,但是你需要调用app.exec();来启动事件循环处理。否则永远不会触发连接。

此外,如果您处于发布模式,那么您可能看不到qDebug()

的输出

答案 1 :(得分:2)

* 请参阅下面的编辑

首先,您无法将信号连接到某个函数,您应该将其连接到某个类的插槽,并且此类的实例也应该提供给QObject::connect

所以要做的第一件事就是定义一个带槽的类:

// file 'C.h'
#ifndef __C_H__
#define __C_H__

#include <QtGui>

class C : public QObject{
    Q_OBJECT

public slots:
    static void insert()
    {
        qDebug() << "pressed";
    }
};

#endif

请注意,此类必须继承QObject并在其中包含Q_OBJECT个关键字。 您必须将此类声明放在*.h文件中(Q_OBJECT文件中不能有*.cpp,因为Qt不会看到它。

既然你有一个带插槽的课程,你可以使用QObject::connect,正确的方法是:

  QObject::connect(button, SIGNAL(clicked()), &c, SLOT(insert()));

请注意,连接时必须使用SIGNAL()宏作为信号,并使用SLOT()宏作为插槽。

因此main.cpp中的代码应如下所示:

  #include "C.h"

  int main(int argc,char *argv[])
  {

      QApplication app(argc,argv);
      QPushButton *button=new QPushButton("button");
      button->setGeometry(50,100,150,80);
      C c;
      QObject::connect(button, SIGNAL(clicked()), &c, SLOT(insert()));
      button->show();

      return app.exec();
   }

您看到我如何向&c函数提供接收器对象(connect())的实例,即使您的函数是static,也必须这样做。

最后你必须app.exec();,否则你的程序将没有消息循环。

修改

我错过了关于Qt 5的问题。对于Qt 5.0,答案是错误的。