QT5

k5bg

一.下载安装QT5

QT是一个跨平台的C++图形用户界面应用程序框架,主要用来开发图形用户界面(Graphical User Interface,GUI)

QT除了可以绘制漂亮的界面(包括控件/布局/交互),还可以多线程/访问数据库/图像处理/音视频处理/网络通信/文件操作等

Windows下的GUI解决方案:QT/MFC/WTL/DirectUI

Linux下的GUI解决方案:QT/GTK+

 

QTSource和QTCreator的下载地址

 

这里给大家推荐几个国内著名的 Qt 镜像网站,主要是各个高校的:

中国科学技术大学:http://mirrors.ustc.edu.cn/qtproject/
清华大学:https://mirrors.tuna.tsinghua.edu.cn/qt/
北京理工大学:http://mirror.bit.edu.cn/qtproject/
中国互联网络信息中心:http://mirror.bit.edu.cn/qtproject/

 

https://www.qt.io/offline-installers
https://download.qt.io/archive/qt/5.14/5.14.2/

 

使用mingw编译,自带gcc编译器合gdb调试器(新手推荐)
qt-opensource-windows-x86-mingw492-5.5.1.exe

qt-opensource-windows-x86-msvc2013-5.5.0.exe
qt-vs-addin-1.2.4-opensource.exe

 

1.模块

(1)基础模块

Qt Core
    提供核心的非GUI功能,所有模块都需要这个模块.这个模块的类包含了动画框架 定时器 各个容器类 时间日期类 事件 IO JSON 插件机制 智能指针 图形(矩形 路径等) 线程 XML等

    需要添加头文件<QtCore>

Qt GUI
    提供GUI程序的基本功能,包含与窗口系统的集成 事件处理 OpenGL和OpenGL es继承 2D图像 字体 拖放等.这些类一般用于Qt用户界面类使用,也可以访问底层的OpenGL es图像API.

Qt Multimedia
    提供视频 音频 收音机以及摄像头等功能

    需要在pro文件中添加 QT + = multimedia,需要添加头文件<QtMultimedia>

Qt Network
    提供跨平台的网络功能

    需要在pro文件中添加 QT + = network,需要添加头文件<QtNetwork>

Qt Qml
    提供QML(脚本语言,提供js交互机制)使用的C++ API

    需要在pro文件中添加 QT + = qml,需要添加头文件<QtQml>

Qt Quick
    允许在程序中嵌入Qt Quick(一种基于Qt的高度动画的用户界面,适合移动平台开发)

    需要在pro文件中添加 QT + = quick,需要添加头文件<QtQuick>

Qt SQL
    允许使用SQL访问数据库

    需要在pro文件中添加 QT + = sql,需要添加头文件<QtSql>

Qt Test
    提供Qt程序的单元测试功能

    需要在pro文件中添加 QT + =testlib,需要添加头文件<QtTest>

Qt Webkit
    基于WebKit2的实现以及一套全新的QML API

 


 

 

(2)扩展模块

...

 

 

二.QT5开发工具

 

 

三.QT5数据类型

1.字符串类型(QString) 

//增加字符串

(1) +

QString str1 = "Welcome";
str1 = str1 + "to you!";
 
QString str2 = "Hello";
str +="World";

(2) QString::append()

QString str1 = "Welcome";
QString str2 = "to";
 
str1.append(str2);
str1.append("you!");

(3) QString::sprintf()

String str;
str.sprintf("%s", "Welcome");
str.sprintf("%s", "to you!");
str.sprintf("%s %s", "Welcome", "to you!");

(4) QString::arg()

QString str;
str = QString("%1 was born in %2").arg("John").arg(1982);

 

//删除字符串

。。。

 

//更改字符串

...

 

//查询字符串

(1) QString::startsWith()

/ 判断一个字符串是否以某个字符串开头<br>QString str = "Welcome to you!"
str.startsWith("Welcome", Qt::CaseSensitive);     //返回true
str.startsWith("you", Qt::CaseSensitive);         //返回false

(2) QString::endsWith()

// 判断一个字符串是否以某个字符串结尾

(3) QString::contains()

// 判断一个指定的字符串是否出现过<br>QString str = "Welcome to you!";<br>str.contains("Welcome", Qt::CaseSensitive);  //返回true

 

//字符串比较

(1)  大于小于等于

operator < (const QString&)  // 比较一个字符串是否小于另一个字符串,如果是返回true

operator <= (const QString&)  // 比较一个字符串是否小于等于另一个字符串,如果是返回true

operator == (const QString&)    // 比较两个字符串是否相等,如果相等返回true

operator >= (const QString&)    // 比较一个字符串是否大于等于另一个字符串,如果是返回true 

(2) localeAwareCompare()

localeAwareCompare(const QString&, const QString&)  // 比较两个字符串,如果小于返回负整数值,如果相等返回0,如果大于返回正整数值

(3) compare()

compare(const QString&, const QString&, Qt::CaseSensitivity)  // 是否进行大小写比较,类似localeAeareCompare()

 

//字符串转换

QString::toInt()

QString::toDouble()

QString::toFloat()

QString::toLong()

QString::toLongLong()

 

QString::toAscii()

QString::toLatin1()

QString::toUtf8()

QString::toLocal8Bit()


bool ok;
QString valueStr = ui->lineEdit->text();
int valueInt = valueStr.toInt(&ok);
double area = valueInt * valueInt *PI;
QString tempStr;
ui->lineEdit->setText(tempStr.setNum(area));<br><br>QString str = "125";<br>bool ok;<br>int hex = str.toint(&ok, 16);<br>int dec = str.toInt(&ok, 10);

 

//字符串判断

QString().isNull();

QString().isEmpty()

 

//正则表达式

使用正则表达式可以快速完成处理字符串的一些操作,如验证 查找 替换和分割

Qt的QRegExp类是正则表达式的表示类,它基于Perl的正则表达式语言

正则表达式由表达式(expressions) 量词(quantifiers)和断言(assertions)组成

 

 

2.日期类型(QData)

 

3.时间类型(QTime)

 

4.顺序容器类型

QT的顺序容器类型有QList QLinkedList QVector QStack QQueue

 

//QVector<T>

QVertor<T>在相邻的内存中存储数据类型T

QVertor<T>既可以用下标访问,也可以使用迭代器访问

 

//QList<T>

QList<T>可以使用下标访问

QList::append()

QList::prepend()

QList::insert()


#include<QList>

int main(int argc, char* argv)
{
  QList<QString> list;
  {
    QString str("This is a test string"
);
    list << str;
  }
}

 

//QLinkedList<T>

QLinkedList<T>是一个链式列表,它以非连续的内存块保存数据

QLinkedList<T>无法用下标访问,只能使用迭代器访问

 

//QStack

...

 

//QQueue

...

 

5.关联容器类型

Qt的关联容器类QMap QMultiMap QHash  QMultiHash  QSet

 

//QMap

QMap<QString, QString> map;
map.insert("beijing", "111");
map.insert("shanghai", "021");
map.insert("nanjing", "025");
 
QMapIterator<QString, QString> i(map);
for (;i.hasNext();)
    qDebug() << " " << i.key() << " " << i.next().value();
QMutableMapIterator<QString, QString> mi(map);
if (mi.findNext("111"))
    mi.setValue("010");
QMapIterator<QString, QString> modi(map);<br>qDebug() << " ";
for (modi = map.constBegin(); modi != map.constEnd(); ++modi)
    qDebug() << " " << modi.key() << " " <<modi.next().value();

 

//QSet

...

 

//QHash

...

 

//QMultiHash

...

 

//QMultiMap

...

 

//QVariant

QVariant类能够保存很多QT类型的值,包括QColor QBrush QFont QPen QRect QSize等

 

 

四.QT5语法

 1.元对象

QT使用元对象编译器(Meta Object Compiler,moc),实现了元对象(Meta Object System,mos)机制,为标准C++增加了一些特性:

信号槽机制,用于解决对象之间的通讯
可查询可设计的对象属性
强大的事件机制以及事件过滤器
基于上下文的字符串翻译机制(国际化),用 tr() 函数实现
复杂的定时器实现,用于在事件驱动的GUI中嵌入能够精确控制的任务集成
层次化的可查询的对象树,提供一种自然的方式管理对象关系
智能指针(QPoint),在对象析构之后自动设为0,防止野指针
能够跨越库边界的动态转换机制

 

元对象系统是基于以下3个条件:

(1)基类QObject:任何需要使用元对象系统功能的类必须继承自QObject类

(2)Q_OBJECT宏:必须在类的私有声明区声明Q_OBJECT宏(默认为private)

(3)元对象编译器(Meta-Object Compiler,moc):为QObject子类实现元对象特性提供必要的代码

 

 

2.信号槽 

QT编程中信号与槽用于处理界面各个组件的交互,类似与MFC的消息循环和绑定

注意:在使用信号与槽的类中,必须在类的定义中加入宏定义Q_OBJECT

信号(Signal)就是在特定情况下被发射的时间,类似于鼠标单击时发生clicked()信号

槽(Slot)是对信号响应的函数

 


 

 

(1)ui文件设计信号与槽函数

在需要设计槽的控件(触发控件)上右键->转到槽    

或者直接按下F4进入快速选择信号和槽函数

选择相应的信号之后就会跳转到该信号函数

lineEdit 文本编辑框
    textChanged(QString)

    testEdited(QString)   

pushButton 按钮
    clicked()

    clicked(bool)

    pressed()

 

//helloDialog.h

class HelloDialog : public QMainWindow {

// 声明槽函数
private slots:
    void on_pushButton_clicked();
}

 

//helloDialog.cpp

void HelloDialog::on_pushButton_clicked() {

    ui->lineEdit->setText("k5");
}

 


 

 

(2)内置的信号与槽函数

如果不在.ui文件里面直接绑定,就必须用connect()进行绑定

 connect(

ui文件下的控件名称

控件自带的信号函数

自定义的对象

自定义的槽函数

)

 

//helloDialog.h
 
class HelloDialog{
     
public:
    void initSignalSlots();  //初始化信号与槽连接
<br>// 声明槽函数
private slots:
    void changeData();
}

 

//helloDialog.cpp
 
void HelloDialog::initSignalSlots() {
     
    connect(ui->pushButton,SIGNAL(cliked()),this,SLOT(changeData));
}
 
void HelloDialog::changeData(){
    ui->lineEdit->setText("k5");
}

 


 

 

(3)自定义信号与槽函数

除了使用QT内置的信号函数和槽函数,也可以自定义信号和槽函数.

创建两个类继承QObject类,添加Q_Object宏,用signals和slots标记信号和槽函数

 

// test.h
 
#ifndef TEST_H
#define TEST_H
 
#include <QObject>
#include <QDebug>
 
class test : public QObject
{
    Q_OBJECT
 
public:
    test();
 
    void send(){
        emit testcall();
    }
 
signals:
    void testcall();
 
public slots:
    void testreveive();
 
}
 
#endif  // TEST_H

 

// test.cpp<br><br>#include "test.h"
 
test::test()
{
 
}
 
void test::testreceive(){
    qDebug() << "receive";
}

 

// mainwindow.cpp
 
#include "ui_mainwindow.h"
#include "test.h"
 
MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    test t;
    connect(&t, &test::testcall, &t, &test::testreceive);
    t.send();
}

 

注意:使用 signals 标记信号函数,信号是一个函数声明,返回void,不需要实现函数代码

  使用 emit 可以发送信号

 

 

 

五.QT5窗口界面框架

在项目Application中:

QT Widgets Application(桌面QT应用)

QT Console Application(控制台QT应用)

QT for Python-Empty / Window(用Python开发QT应用)

QT Quick Application-Empty / Scroll / Stack /Swipe(移动平台开发QT应用)

 

1.QWidget

 

QWidget widget;
widget.setWindowTitle(QObject::tr("k5"));
widget.resize(400, 300);
widget.move(200, 100);
widget.show();

int x = widget.x();
qDebug("x:%d", x);

int y = widget.y();
qDebug("y:%d", y);

 

Widget 窗口主要是在上面放置布局和控件,可以嵌入到主窗体中

 

(1)窗体框架

// widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = nullptr);
    ~Widget();

private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

 

// widget.cpp

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}

 

// main.cpp

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

 


 

 

(2)配置

//QTTest.pro

QT    +=    core gui

greaterThan(QT_MAJOR_VERSION, 4) : QT += widgets

CONFIG    +=    c++11

DEFINES   +=    QT_DEPRECATED_WARNINGS

SOURCE    +=    \
    main.cpp    \
    mainwindow.cpp

HEADERS    +=    \
    mainwindow.h

FORMS    +=    \
    mainwindow.ui

TRANSLATIONS    +=    \
    QTTest_zh_CN.ts

qnx    :    target.path    =    /tmp/&&{TARGET}/bin
else    :    unix     :!    android    :    target.path    =    /opt/$${TARGET}/bin
!isEmpth(target.path)    :    INSTALLS    +=    target

 

//mainwindow.ui
<?xml version = "1.0" encoding = "UTF-8"?>
<ui version = "4.0">
    <class> MainWindow </class>
    <widget class = "QMainWindow" name = "MainWindow">
        <property name = "geometry">
            <rect>
                <x>0</x>
                <y>0</y>
                <width>800</width>
                <height>600</height>
            </rect>
         </property>
         <property name = "windowTitle">
             <string>Maindow</string>
         </property>
     <widget class = "QWidget" name = "centralwidget"/>
     <widget class = "QMenuBar" name = "menubar">
         <property name = "geometry">
             <rect>
                <x>0</x>
                <y>0</y>
                <width>800</width>
                <height>26</height>
             </rect>
          </property>
      </widget>
      <widget class = "QStatusBar" name = "statusbar" />
      </widget>
      <resources/>
      <connections/>
</ui>   

 


 

 

(3)成员函数

QWidget 类继承于 QObject 类和 QPaintDevice 类

void QWidget::resize(int w, int h)

void QWidget::resize(const QSize& )

 

QSize QWidget::size() const

void QWidget::show()


QWidget::x()

QWidget::y()

QWidget::pos()

QWidget::find()

QWidget::font()

QWidget::grab()

QWidget::hide()

QWidget::mask()

QWidget::move()

QWidget::rect()

QWidget::close()

QWidget::lower()

QWidget::mapTo()

QWidget::raise()

QWidget::style()

QWidget::winId()

QWidget::cursor()

QWidget::layout()

QWidget::locale()

QWidget::render()

 

QWidget::scroll()

QWidget::update()

QWidget::window()

QWidget::actions()

QWidget::childAt()

QWidget::isModal()

QWidget::mapFrom()

QWidget::palette()

QWidget::repaint()

QWidget::setFont()

QWidget::setMask()

QWidget::toolTip()

QWidget::baseSize()

QWidget::fontInfo()

QWidget::geometry()

QWidget::hasFocus()

QWidget::isHidden()

QWidget::isWindow()

QWidget::setFocus()

QWidget::setStyle()

QWidget::sizeHint()

QWidget::addAction()

QWidget::clearMask()

QWidget::framwSize()

QWidget::grabMouse()

QWidget::isEnabled()

QWidget::isVisible()

QWidget::setCursor()

QWidget::setHidden()

QWidget::setLayout()

QWidget::setLocale()

QWidget::statusTip()

QWidget::whatsThis()

QWidget::addActions()

QWidget::adjustSize()

QWidget::clearFocus()

QWidget::focusProxy()

QWidget::isTopLevel()

QWidget::setEnabled()

QWidget::setPalette()

QWidget::setToolTip()

QWidget::setVisible()

QWidget::showNormal()

QWidget::sizePolicy()

QWidget::stackUnder()

QWidget::styleSheet()

QWidget::underMouse()

 

 

2.QDialog

(1)窗口框架

 

QDialog类继承与QWidget类

注意:添加hellodialog.ui文件的时候,要把里面的 <class>HelloDialog</class>

                       <widget class = "QDialog" name = "HelloDialog"> 改过来,不然会无法识别 ui 这个指针

 

// hellodialog.h

#ifndef HELLODIALOG_H
#define HELLODIALOG_H

#include <QDialog>

namespace Ui{
    class HelloDialog;
}

class HelloDialog : public QDialog{

    Q_OBJECT
public:
    explicit HelloDialog(QWidget* parent = nullptr);
    ~HelloDialog();

private:
    Ui::HelloDialog* ui;
};


#endif // HELLODIALOG_H

 

// hellodialog.cpp#include "hellodialog.h"
#include "ui_hellodialog.h"


HelloDialog::HelloDialog(QWidget* parent) :
    QDialog(parent),
    ui(new Ui::HelloDialog)
{
    ui->setupUi(this);

}

HelloDialog::~HelloDialog()
{
    delete ui;
}

 

// main.cpp

#include "hellodialog.h"
#include <QApplication>

int main(int argc, char* argv[])
{
    QApplication a(argc, argv);
    HelloDialog w;
    w.show();

    return a.exec();
}

 

(2)附加窗口

//模态对话框

QDialog* dialog = new QDialog(this);
dialog->setModal(true);
dialog->show();QDialog dialog;dialog.setModal(true);dialog.show()

 

//非模态对话框

QDialog* dialog = new QDialog(this);
dialog->show();

QDialog dialog;
dialog.show()

 

 (3)对话框状态

QDialog dialog;
if (dialog.exec() == QDialog::Accepted) 

 

QDialog类是所有对话框窗口类,对话框窗口是一个经常用来完成短小任务或者和用户进行简单交互的顶层窗口

对话框分为模态对话框和非模态对话框

模态对话框在关闭它之前,不能与同一个应用程序的其他窗口进行交互

非模态对话框既可以和它交互,也可以和同一个应用程序的其他窗口交互

 

模态对话框用 exec() 函数显示,或者在 show() 函数之前加上 setModal(true)

非模态对话框用 show() 函数显示

 

// dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>

namespace Ui {
class Dialog;
}

class Dialog : public QDialog
{
    Q_OBJECT

public:
    explicit Dialog(QWidget *parent = nullptr);
    ~Dialog();

private:
    Ui::Dialog *ui;
};

#endif // DIALOG_H

 

// dialog.cpp

#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
}

Dialog::~Dialog()
{
    delete ui;
}

 

// main.cpp

#include "dialog.h"
#include <QApplication>

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

    Dialog w;
    // w.setModal(true);
    // w.exec();
    w.show();

  
    return a.exec();
}

 

3.QMainWindow

MainWindow类提供一个有菜单条 工具栏 状态条的主应用程序窗口

它是最常见的GUI主窗口形式,它由外到内依次是菜单栏 状态栏 工具栏 停靠窗口 中心窗口

 

 

//One.pro

#-------------------------------------------------
#
# Project created by QtCreator 2019-06-18T13:29:09
#
#-------------------------------------------------
 
# 表示项目加入core gui模块,用于GUI设计的类库模块
QT       += core gui
 
# 条件执行语句,当QT主版本大于4才加入widgets模块
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
 
# 生成的目标可执行文件名称
TARGET = One
 
# 项目使用的模板是app,一般应用程序
TEMPLATE = app
 
DEFINES += QT_DEPRECATED_WARNINGS
 
CONFIG += c++11
 
#QT会自动修改以下新增/删除文件
SOURCES += \
        main.cpp \
        mainwindow.cpp
 
HEADERS += \
        mainwindow.h
 
FORMS += \
        mainwindow.ui
 
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

 

//mainwindow.h

QWidget是所有用户界面对象的基类,QMainWindow和QDialog都是QWidget的子类

QMainWindow类提供一个菜单条/工具条/状态条的主应用程序窗口

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
 
#include <QMainWindow>
 
namespace Ui {
class MainWindow;
}
 
class MainWindow : public QMainWindow
{
    Q_OBJECT
 
public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
 
private:
    Ui::MainWindow *ui;
};
 
#endif // MAINWINDOW_H

 

//mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}
 
MainWindow::~MainWindow()
{
    delete ui;
}

 

//main.cpp

#include "mainwindow.h"
#include <QApplication>
 
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
 
    return a.exec();
}

 

//hellodialog.ui

可视化设计的窗体的定义文件,是一个XML文件

 

// 创建菜单栏
QMenu* file = menuBar()->addMenu(tr("k5"));

// 创建工具栏
QToolBar* toolBar = addToolBar(tr("k4"));

 

 

六.QT5控件

Layouts

Spacers

Buttons

Item Views(Model-Based)

Item Widgets(Item-Based)

Containers

Input Widgets

Display Widgets

Label

Text Browser

Graphics View

Calendar Widget

LCD Number

Progress Bar

Horizontal Line

Vertical Line

OpenGL Widget

QQuickWidget

 

1.布局排版控件

在QT组件面板中有Layouts和Spacers两个组件面板

注意:布局排版控件不显示

 

//Layouts(布局)

Vertical Layout:垂直方向布局,组件自动在垂直方向上分布 Horizontal Layout:水平方向布局,组件自动在水平方向上分布 Grid Layout:网格状布局,网格布局大小改变时,每个网格的大小都改变 Form Layout:窗体布局,与网格状布局类似,但是只有最右侧的一列网格会改变大小 (
1)ui文件实现 (2)代码实现

 

//Spacers(排版)

Horizontal Spacer:一个用于水平分隔的空格 Vertival Spacer:一个用于垂直分隔的空格 (
1)ui文件实现 (2)代码实现

 

2.按钮控件

 

按钮控件一共有六种:pushButton
                 toolButton
                 radioButton
                 checkBox
                 commandLinkButton
                 dialogButtonBox

 

//pushButton

(1)创建pushButton

// mainWindow.h<br><br>#include <QPushButton>
 
class MainWindow : public QMainWindow
{
 
private:
    QPushButton* pushButton;                  
}

// mainWindow.cpp
 
MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
 
    pushButton=new QPushButton(this); 
}

(2)pushButton成员函数

void setFlat(bool);
void setMenu(QMenu* menu);
void showMenu();
void setDefault(bool);
void setAutoDefault(bool);

QString tr(const char* s, const char* c, int n);
QString QAbstractButton::tr(const char* s, const char* c, int n);
QString QWidget::tr(const char* s, const char* c, int n);
QString QObject::tr(const char* s, const char* c, int);

pushButton->setText(tr("显示面积"));

 

 3.输入控件

输入控件一共有16种:comboBox

           fontComboBox

           lineEdit

           testEdit

           plainTextEdit

           spinBox

           doubleSpinBox  

           timeEdit

           dateEdit

           date/timeEdit

           dial

           horizontalScrollBar

           verticalScrollBar

           horizontalSlider

           verticalSlider

           keySequenceEdit

 

(1)lineEdit

// mainWindow.h
 
#include <QLineEdit>
  
class MainWindow : public QMainWindow
{
  
private:
    QLineEdit* lineEdit;                 
}


// mainWindow.cpp
  
MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
  
    lineEdit=new QLineEdit(this);
}

 

 4.显示控件

 

在显示控件(Display Widgets)中,有10种类型的显示控件

Label

Text Browser

Graphics View

Calendar Widget

LCD Number

Progress Bar

Horizontal Line

Vertical Line

OpenGL Widget

QQuickWidget

 

//Label

#include <QLable>

int main(int argc, char* argv[])
{
    QLabel* label = new QLabel();
    ...
    delete label;
}

 

 

七.QT5绘制

 1.2D绘制

 

QPainter QPaintDevice QPaintEngine三个类来绘制
Qt默认窗口左上角为坐标原点(0,0),水平向右依次增大,水平向左依次减小
              垂直向下依次增大,垂直向上依次减小

QPainter执行绘图操作
QPaintDevice提供绘图设备
QPaintEngine提供接口,可以在不同的设备上绘制

 

//mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

//提供绘图类
#include <QPainter>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

protected:
    void paintEvent(QPaintEvent* );

private:
    Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

 

//mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::paintEvent(QPaintEvent* )
{
    QPainter painter(this);

  //直接绘制
   //painter.drawLine(QPointF(0, 0), QPointF(100, 100));

  //添加画笔和画刷,改变形状和颜色
  QPen pen;                   //画笔
  pen.setColor(QColor(255, 0, 0));
  QBrush brush(QCOlor(0, 255, 0, 125));  //画刷
  painter.setPen(pen);            //添加画笔
  painter.setBrush(brush);          //添加画刷
  painter.drawRect(50, 50, 200, 100);   //绘制矩形  
}

 

2.3D绘制

 

Qt中提供了QtOpenGL模块来显示3D图形
Qt提供了QGLWidget类来渲染OpenGL图形
继承的虚函数:
1.initializeGL():设置OpenGL渲染环境,定义显示列表等,该函数只在第一次调用resizeGL()或paintGL()前调用一次
2.resizeGL():设置OpenGL的视口、投影等,每次部件改变大小时都会调用该函数
3.paintGL():渲染OpenGL场景,每当部件需要更新时都会调用该函数

 

//QT 3D

C++ aplication:
qmake .pro file这个配置文件中添加

QT += 3dcore 3drender 3dinput 3dlogic 3dextras 3danimation

Qt Quick applicaton:

QT += 3dcore 3drender 3dinput 3dlogic 3dextras qml quick 3dquick 3danimation


在引用头文件中包含

#include <Qt3DCore>
#include <Qt3DRender>
#include <Qt3DInput>
#include <Qt3DLogic>
#include <Qt3DExtras>
#include <Qt3DAnimation>

 

//QT OpenGL

#include <QtOpenGL>

QT += opengl

 

 

八.QT5多线程和多进程

1.多线程

 

QThread是Qt线程中一个公共的抽象类,所有的线程类都是从QThread抽象类中派生的,需要实现QThread中的虚函数run(),通过调用start()函数

 

QThread对多线程的支持:

1.QThreadStorage 提供逐线程数据存储

2.QMutex 互斥锁

3.QMutexLocker 自动互斥锁

4.QReadLocker 和 QWriteLocker 自动读写锁

5.QReadWriteLocker 读写锁

6.QSemphore 互斥信号量

7.QWaiteCondition 等待条件

 

2.多进程

QT通过QProcess类来启动一个程序与其通信

 

QT对多进程的支持:

1.共享内存(shared memory)

2.TCP/IP: C/S程序,网络交互

3.D-Bus:信号槽机制扩展到进程级别

4.QCOP(Qt COmmunication Protocol):QCOP是Qt内部的一种通信协议,只用于 Qt for Embeded Linux版本

 

 

九.QT5网络

 

 

十.QT5文件

 

十一.QT5算法

QT的<QtAlgorithms>和<QtGlobal>模块提供了几种常用算法

qAbs(<T>);

qMax(<T>, <T>);

qRound(<T>);

qSwap(<T>, <T>);

QObject::tr(QString);

 

十二.QT5异常调试

1.QDebug()

//QDebug()能够将调试信息直接输出到控制台

#include <QDebug>
 
int main(int argc, char* argv[])
{
    int x =10;
    int w = 10;
 
    // 字符串的形式输出
    qDebug("%d", x);
 
    // IO流的形式输出
    qDebug() << x << w << endl;
}

 

十三.QT5资源配置

1.加载图片

1.右键项目->Add New->选择 Qt Resource File->输入名称,例如X

2.打开 X.qrc 资源文件,点击 添加前缀,可以修改前缀

3.点击添加文件,把图片路径放进去

4.对于 X.qrc资源文件 可以 Open in Editor,也可以 Open With 编辑器

.qrc 资源文件实际上是XML文件

 

分类:

技术点:

相关文章: