在Ubuntu上编写Qt Helloworld程序


不使用Qt Creator IDE的情况下,我只使用自己喜欢的Emacs和命令行来创建一个hello world工程。

Ubuntu 环境下Gtk与QT编译环境安装与配置

Linux系统下QT环境搭建

Ubuntu下QT控制台程序无法运行的解决方案以及XTerm的配置方法

Ubuntu 10.04下QT4.7.4移植详解

Ubuntu 14.04下安装部署Qt5开发环境

1. 确保/usr/bin/qmake指向Qt 5.2.0安装的qmake

/usr/bin# mv qmake qmake_bk
/usr/bin# ln -s /home/likewise-open/CHN/shu6889/Qt5.2.0/5.2.0/gcc_64/bin/qmake ./qmake

2. 写代码:

创建helloworld目录,添加main.cc文件

#include <QtWidgets/QApplication>
#include <QtWidgets/QLabel>
int main(int argc, char *argv[]) {
  QApplication app(argc, argv);
  QLabel hello("<center>Welcome to my first WikiHow Qt program</center>");
  hello.setWindowTitle("My First WikiHow Qt Program");
  hello.resize(400, 400);
  hello.show();
  return app.exec();
}

3. 创建project文件

在helloworld目录下,运行下面的命令:

qmake -project

现在,我得到了helloworld.pro文件。

######################################################################
# Automatically generated by qmake (3.0) ?? 12? 16 15:49:40 2013
######################################################################
TEMPLATE = app
TARGET = helloworld
INCLUDEPATH += .
# Input
SOURCES += main.cc

4. 编译

运行qmake,不带参数。这样就得到了Makefile文件。

qmake
make

得到-lGL的链接错误,安装mesa

 apt-get install libgl1-mesa-dev

但是得到了一些新的链接错误:

main.o: In function `main':
main.cc:(.text.startup+0x27): undefined reference to `QApplication::QApplication(int&, char**, int)'
main.cc:(.text.startup+0x56): undefined reference to `QLabel::QLabel(QString const&, QWidget*, QFlags<Qt::WindowType>)'
main.cc:(.text.startup+0x84): undefined reference to `QWidget::setWindowTitle(QString const&)'
main.cc:(.text.startup+0xa9): undefined reference to `QWidget::resize(QSize const&)'
main.cc:(.text.startup+0xb1): undefined reference to `QWidget::show()'
main.cc:(.text.startup+0xb6): undefined reference to `QApplication::exec()'
main.cc:(.text.startup+0xc1): undefined reference to `QLabel::~QLabel()'
main.cc:(.text.startup+0xc9): undefined reference to `QApplication::~QApplication()'
main.cc:(.text.startup+0xe5): undefined reference to `QApplication::~QApplication()'
main.cc:(.text.startup+0x106): undefined reference to `QLabel::~QLabel()'
main.cc:(.text.startup+0x118): undefined reference to `QLabel::~QLabel()'
collect2: error: ld returned 1 exit status
make: *** [helloworld] Error 1

在helloworld.pro文件中添加一行:

QT += widgets

重新编译。好了。

运行hellowordl程序,看到Qt窗口了。

当切换到Windows上开发时,可以不使用命令行开发。直接用Qt Creator打开这个helloworld.pro文件,会默认使用一些配置。编译运行,成功了。

Qt 的详细介绍:请点这里
Qt 的下载地址:请点这里

相关内容