0

操作系统:windows xp SP2,编译器:Code::Blocks ver。10.05,Qt 4.6

我最近开始学习Qt。起初,简单的 tut 示例一切顺利。我很快遇到了一个无法编译的示例,并意识到出了点问题。

这是代码:

#include <QWidget>
#include <QApplication>
#include <QPushButton>
#include <QLabel>
#include <QDesktopWidget>


class Communicate : public QWidget
{
  Q_OBJECT

  public:
    Communicate(QWidget *parent = 0);

  private slots:
    void OnPlus();
    void OnMinus();

  private:
    QLabel *label;

};


 void center(QWidget *widget, int w, int h)
{
  int x, y;
  int screenWidth;
  int screenHeight;

  QDesktopWidget *desktop = QApplication::desktop();

  screenWidth = desktop->width();
  screenHeight = desktop->height();

  x = (screenWidth - w) / 2;
  y = (screenHeight - h) / 2;

  widget->move( x, y );
}


Communicate::Communicate(QWidget *parent)
    : QWidget(parent)
{
  int WIDTH = 350;
  int HEIGHT = 190;

  resize(WIDTH, HEIGHT);

  QPushButton *plus = new QPushButton("+", this);
  plus->setGeometry(50, 40, 75, 30);

  QPushButton *minus = new QPushButton("-", this);
  minus->setGeometry(50, 100, 75, 30);

  label = new QLabel("0", this);
  label->setGeometry(190, 80, 20, 30);

  connect(plus, SIGNAL(clicked()), this, SLOT(OnPlus()));
  connect(minus, SIGNAL(clicked()), this, SLOT(OnMinus()));


  center(this, WIDTH, HEIGHT);

}

void Communicate::OnPlus()
{
  int val = label->text().toInt();
  val++;
  label->setText(QString::number(val));
}

void Communicate::OnMinus()
{
  int val = label->text().toInt();
  val--;
  label->setText(QString::number(val));
}



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

  Communicate window;

  window.setWindowTitle("Communicate");
  window.show();

  return app.exec();
}

当我尝试打开它时,我收到以下消息:

obj\Release\main.o:main.cpp|| 未定义对“vtable for Communicate”的引用|

obj\Release\main.o:main.cpp|| 未定义对“vtable for Communicate”的引用|

obj\Release\main.o:main.cpp|| 未定义对“vtable for Communicate”的引用|

obj\Release\main.o:main.cpp|| 未定义对“vtable for Communicate”的引用|

obj\Release\main.o:main.cpp|| 未定义对“vtable for Communicate”的引用|

obj\Release\main.o:main.cpp|| 更多未定义的对“vtable for Communicate”的引用如下|

||=== 构建完成:6 个错误,0 个警告 ===|

我正在寻找 code:: blocks 论坛的解决方案,并了解到应该安装 Qt 插件。

所以,我安装了 QtWorkbench 0.6.0 alpha -> qt 插件,但没有任何改变。

欢迎任何建议。

4

2 回答 2

2

您是否对这个文件进行了 moc 并包含了 moc 输出以进行编译?

每当您使用 Q_OBJECT 宏时,您必须在该文件上使用 Qt 的 moc 命令来生成一个新的 cpp 文件,该文件也应该包含在要与您的项目一起编译的文件中。另外,我相信你只能 moc 一个头文件,所以你必须将你的类定义移动到一个单独的文件并 moc 那个文件。

我不知道它对你的 IDE 是如何工作的,但是在命令行上你会调用类似的东西

<QT4 directory>\bin\moc.exe myfile.h -o moc_myfile.cpp

然后在项目中也包含文件 moc_myfile.cpp。

在某些 IDE 中,这就是 Qt 插件为您所做的;它自动执行所有这些步骤或使用不需要显式 moc'ing 的 qmake。在 Visual Studio 中,我只使用自定义构建步骤。

于 2010-06-22T20:58:20.740 回答
0

尝试在 Communication 构造函数中调用 center()。我相信这可能会导致您的错误。

于 2010-06-22T20:40:21.700 回答