接上文,這篇學學QT中基本控件的使用和QApplication對象
1.什么是QApplication?
文檔說明:
The QApplication class manages the GUI application's control flow and main settings.
Application類管理GUI程序控制流和主要參數設置
QApplication繼承于QCoreApplication。后者提供了控制臺程序的事件流
2.基本控件的使用例子:
#include <QApplication>
#include <QLabel>
#include <QPalette>
#define QT_HTML
QLabel* label = NULL;
void initlabel()
{
#ifndef QT_HTML
label = new QLabel("Hello Qt!");
#else
label = new QLabel("<h2><i>Hello</i><font color=red>Qt!</font></h2>");
#endif
//! set size
label->setBaseSize(64,48);
//! set alignment
label->setAlignment(Qt::AlignHCenter);
//! sht background color
QColor bk(100,100,125);
QPalette palette(bk);
label->setPalette(palette);
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
app.setApplicationName("QT Test");
initlabel();
label->show();
return app.exec();
}
QLabel是QT中的標簽控件它具有控件的一般屬性比如設置大小setBaseSite,設置對齊格式,當然也可以設置背景色或者圖片-這都是通過QPalette調色板來實現的
需要說明的是QT中的控件文本可以使用Html語法的文本來操作具體如上。
那覺這個功能比較給力!
3.那么什么是QPalette?
QPalette負責控制控件狀態的顏色組-注意是控件狀態。
那么對一個控件每個狀態的顏色都可以是不一樣的咯
至于QPalette的詳細功能和使用方法以后需要的時候再看吧
4.基本的信號鏈接使用例子
#include <QApplication>
#include <QPushButton>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QPushButton *button = new QPushButton("Quit");
//! when click button, app exit.
QObject::connect(button, SIGNAL(clicked()),&app, SLOT(quit()));
button->show();
return app.exec();
}
5.一個復雜點的例子
#include <QApplication>
#include <QHBoxLayout>
#include <QSlider>
#include <QSpinBox>
#include <QIcon>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget* widget = new QWidget;
QIcon icon("config.png");
widget->setWindowIcon(icon);
widget->setWindowTitle("Using QT");
QSlider* slider = new QSlider(widget);
slider->setRange(0,99);
QSpinBox* spinbox = new QSpinBox(widget);
spinbox->setRange(0,99);
widget->show();
return app.exec();
}
編譯運行可以看出QWidget中默認的布局管理器是豎直向下排列的
在QT中可以通過setWindowIcon來設置窗體圖標
通過setWindowTitle設置窗體標題
6.加上布局管理器和信號連接的話代碼大致應該是這個樣子
#include <QApplication>
#include <QHBoxLayout>
#include <QSlider>
#include <QSpinBox>
#include <QIcon>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget* widget = new QWidget;
QIcon icon("config.png");
widget->setWindowIcon(icon);
widget->setWindowTitle("Using QT");
QSlider* slider = new QSlider(widget);
slider->setRange(0,99);
QSpinBox* spinbox = new QSpinBox(widget);
spinbox->setRange(0,99);
QHBoxLayout* layout = new QHBoxLayout;
layout->addWidget(spinbox);
//! adjust slider's direction
slider->setOrientation(Qt::Horizontal);
layout->addWidget(slider);
spinbox->setValue(28);
//! connect signals and slots
QObject::connect(spinbox, SIGNAL(valueChanged(int)),slider,SLOT(setValue(int)));
QObject::connect(slider,SIGNAL(valueChanged(int)),spinbox,SLOT(setValue(int)));
widget->setLayout(layout);
widget->show();
return app.exec();
}
需要說明的是在這里QSlider,QPinBox控件是互動
編譯程序并運行界面如下:

這是關于QT的第六篇筆記
總結下吧
QT功能還是很強大貼心的
比較容易上手
不過有2點我感覺不大舒服的地方是對這個變量命名格式有點不大喜歡
比如setValue我喜歡寫成SetValue.
僅此而已