星期三, 八月 06, 2008

Qt4.4 学习笔记(一) HelloWorld

Qt4.4官方教程的第一个例子,即HelloWorld

#include < qapplication >
#include < qlabel >
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QLabel *label = new QLabel("Hello Qt!");
label->show();
return app.exec();
}

命令行,分3步:
1.qmake -project
2.qmake
3.make
执行成功后即可显示


Qt3.x的HelloWorld
#include < QApplication >
#include < QPushbutton >

int main( int argc, char **argv )
{
QApplication a( argc, argv );

QPushButton hello( "Hello world!", 0 );
hello.resize( 100, 30 );

a.setMainWidget( &hello );
hello.show();
return a.exec();
}
同样的3步
1.qmake -project
2.qmake
3.make
执行后显示
hello.cpp: In function ‘int main(int, char**)’:
hello.cpp:12: error: ‘class QApplication’ has no member named ‘setMainWidget’
make: *** [hello.o] 错误 1
结果你编译出错,原因是因为QT4跟QT3有很多的变化,这可以参考QT4的手册。

在QT4里面没有setMainWidget这个方法,解决方法是直接在.pro文件中添加 QT += qt3support 就行了。

Qt4.4 中文版的HelloWorld
#include < QtGui/QApplication >
#include < QtGui/QWidget >
#include < QtGui/QLabel >
#include < QtCore/QTextCodec >
#include < QtGui/QPushButton >
#include < QtGui/QVBoxLayout >
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
QTextCodec::setCodecForTr(QTextCodec::codecForName("gb18030"));
QWidget* pWidget = new QWidget;
QLabel label(pWidget);
label.setText(QObject::tr("同一个世界,同一个梦想!"));
QPushButton* btn = new QPushButton(QObject::tr("关闭"), pWidget);
QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(&label);
layout->addWidget(btn);
pWidget->setLayout(layout);
QObject::connect(btn, SIGNAL(clicked()), pWidget, SLOT(close()));
pWidget->show();
return app.exec();
}
结果如图





没有评论: