目录
0003 "QString::asprintf()"字符串组合方式
0008 "QString::startsWith()"函数
01 Windows Qt环境安装
略。
02 Linux Qt环境安装
略。
03 Qt Creator工具介绍与使用
使用Qt创建项目后,相当于创建了一个窗口类,在这个窗口类中可以添加其他例如标签、按钮等各种各样的类。如以下案例所示:
widget.h | 该文件创建了窗口类,可在该类下面添加标签类、按钮类; |
widget.cpp | 该文件主要用与对各种类进行初始化设置,包括位置、大小、信号、槽函数等等。 |
main.cpp | 整个项目的入口程序,项目运行时,由此文件启动,通过调用其他文件运行起窗口程序。 |
001 案例01(第一个Qt应用程序)
使用Qt创建项目后:
(1)修改"main.cpp"文件。
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w; //创建一个窗口对象
w.resize(500,500); //设置运行窗口大小
w.setWindowTitle("Qt第一个程序设计"); //设置窗口标题
w.show();
return a.exec();
}
(2)修改"widget.h"文件。
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <qlabel>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
//1:QLabel *labFirst = new QLabel("Qt C++编程",this); //不建议直接在类里边进行初始化
//2:
QLabel *labFirst;
};
#endif // WIDGET_H
(3)修改"widget.cpp"文件。
#include "widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
labFirst = new QLabel("Qt C++编程",this); //在".cpp"文件中初始化标签
labFirst -> setGeometry(50,50,310,100); //设置标签位置和大小
labFirst -> setStyleSheet("QLabel{background-color:green;color:cyan}"); //设置标签背景颜色和字体颜色
labFirst -> setFont(QFont("隶书",22)); //设置字体形式和大小
}
Widget::~Widget()
{
}
(4)运行程序。
04 Qt信号与槽机制
信号(signal):是在特定情况下被发射的通知。
槽(slot):是对信号进行响应的函数。
信号与槽关联是用函数QObject::connect()实现的。
connect()需要使用哪些参数刻如下查看:
001 信号和槽执行参数
[static] QMetaObject::Connection QObject::connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type = Qt::AutoConnection)
参数1 sender | 发出信号的对象 |
参数2 signal | sender对象的信号 |
参数3 receiver | 信号接者 |
参数4 method | receiver对象的槽函数,当检测到sender信号,receiver对象调用method方法 |
002 信号与槽机制连接方式
(1)一个信号可以与另一个信号相连;
connect(object1,SIGNAL(signal1),object2,SIGNAL(signal2));
(2)一个信号可以跟多个槽相连;
connect(object1,SIGNAL(signal1),object2,SIGNAL(slot2));
connect(object1,SIGNAL(signal1),object3,SIGNAL(slot3));
(3)同一个槽可以响应多个信号;
connect(object1,SIGNAL(signal1),object2,SIGNAL(slot2));
connect(object3,SIGNAL(signal3),object2,SIGNAL(slot2));
(4)常用链接方案:
connect(object1,SIGNAL(signal1),object2,SIGNAL(slot2));
003 信号和槽进制优势
(1)松散耦合:
信号和槽之间无需知道谁使用自己或自己被谁使用,降低了信号与槽之间的耦合度,使得程序不容易崩溃。
(2)类型案例:
型号和槽关联参数要相同,一个类若要支持信号和槽,就必须对QObject或QObject的子类继承。Qt信号和槽机制不支持对模板的使用。
004 信号与槽机制效率
增强对象之间通信的灵活性,但是也会损失一些性能。通过传递一个信号来调用槽函数将会比直接调用非虚函数运行速度慢,主要原因有:
(1)多线程的时候,信号可能需要排队等待;
(2)编组/解组传递的参数;
(3)安全地遍历所有的关联;
(4)需要定位接收信号的对象。
005 案例01 计算球体体积
(1)创建项目
(2)修改”main.cpp“文件。
#include "dialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
w.setWindowTitle("计算球体体积");
w.show();
return a.exec();
}
(3)修改”dialog.h“文件。
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <qlabel>
#include <QPushButton>
#include <qlineedit>
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = nullptr);
~Dialog();
private:
QLabel *lab1,*lab2;
QLineEdit *lEdit;
QPushButton *pbt;
private slots:
void CalcBallVolume(); //计算球体体积槽函数
};
#endif // DIALOG_H
(4)修改”dialog.cpp“文件。
#include "dialog.h"
#include<QGridLayout> //表格布局
const static double PI=3.1415;
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
{
//创建一个标签(提示用户输入原器具的半径)
lab1 = new QLabel(this); //生成一个标签对象
lab1 ->setText(tr("请输入圆球的半径:")); //设置标签文本
//创建第2个标签,用来显示圆球计算体积结果
lab2 = new QLabel(this);
//创建一个编辑框控件(专门用来接收用户的输入的圆球半径)
lEdit = new QLineEdit(this);
//创建命令按钮
pbt = new QPushButton(this);
pbt -> setText(tr("输出球体体积"));
/*上述控件若不进行布局,会相互覆盖*/
//表格布局
QGridLayout *mLay = new QGridLayout(this); //创建一个布局对象,并将控件添加到布局中
mLay -> addWidget(lab1,0,0);
mLay -> addWidget(lEdit,0,1);
mLay -> addWidget(lab2,1,0);
mLay -> addWidget(pbt ,1,1);
connect(pbt,SIGNAL(clicked()),this,SLOT(CalcBallVolume()));
// connect(lEdit,SIGNAL(textChanged(QString)),this,SLOT(CalcBallVolume()));
}
Dialog::~Dialog()
{
}
void Dialog::CalcBallVolume()
{
bool isLoop;
QString tempStr;
QString valueStr = lEdit ->text(); //读取用户输入的值
int valueInt = valueStr.toInt(&isLoop); //将用户输入的值转换为int类型用于计算
double dVSum= 4.0/3.0*PI*valueInt*valueInt*valueInt; //计算体积
lab2 ->setText(tempStr.setNum(dVSum)); //将结果显示在窗口中
}
05 字符串类应用与常用数据类型
001 Qt字符串类应用
创建 Qt Console Application。
0001 "+"对字符串进行连接
#include <QCoreApplication> //Qt提供一个事件循环
#include <QDebug> //输出流
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//1:QString提供二元'+'操作符应用,功能一样"+="
QString str1 = "Welcome to ";
str1 = str1 + "learning Qt"; //将“欢迎”与“学习Qt连接起来”
qDebug()<<str1; // 打印信息,但是直接打印会带上一个双引号
qDebug()<<qPrintable(str1);
QString Str2 = "12345";
Str2 += "ABCDE";
qDebug()<<Str2;
return a.exec();
}
0002 "QString::append"连接字符串
#include <QCoreApplication> //Qt提供一个事件循环
#include <QDebug> //输出流
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString str1 = "Good";
QString str2 = "bye";
str1.append(str2);
qDebug()<<qPrintable(str1);
str1.append("Hello World!");
qDebug()<<qPrintable(str1);
return a.exec();
}
0003 "QString::asprintf()"字符串组合方式
C++17:
#include <QCoreApplication> //Qt提供一个事件循环
#include <QDebug> //输出流
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString strtemp;
strtemp= QString::asprintf("%s","Hello ");
qDebug()<<qPrintable(strtemp);
strtemp= QString::asprintf("%s","Hello World!");
qDebug()<<qPrintable(strtemp);
strtemp= QString::asprintf("%s %s","Welcome","to you.");
qDebug()<<qPrintable(strtemp);
}
但是在C++11中,使用方式为:
#include <QCoreApplication> //Qt提供一个事件循环
#include <QDebug> //输出流
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString strtemp;
strtemp.sprintf("%s","Hello ");
qDebug()<<qPrintable(strtemp);
strtemp.sprintf("%s","Hello World!");
qDebug()<<qPrintable(strtemp);
strtemp.sprintf("%s %s","Welcome","to you.");
qDebug()<<qPrintable(strtemp);
return a.exec();
}
0004 "QString::arg()"字符串组合方式
#include <QCoreApplication> //Qt提供一个事件循环
#include <QDebug> //输出流
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString strtemp;
strtemp = QString("%1 was born in %2.").arg("Sunny").arg(2000);
qDebug()<<strtemp;
return a.exec();
}
0005 "QString::insert()"函数
在字符串指定位置插入字符串。
#include <QCoreApplication> //Qt提供一个事件循环
#include <QDebug> //输出流
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString sMem = "三";
QString sFish = "鱼的记忆是秒钟的故事";
sFish.insert(5,sMem);
qDebug()<<sFish;
//插入结果:鱼的记忆是三秒钟的故事
return a.exec();
}
0006 "QString::prepend()"函数
在源字符串开头插入一个字符串。
#include <QCoreApplication> //Qt提供一个事件循环
#include <QDebug> //输出流
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString sMem = "鱼";
QString sFish = "的记忆是三秒钟的故事";
sFish.prepend(sMem);
qDebug()<<sFish;
return a.exec();
}
0007 "QString::replace()"函数
用指定字符串代替源字符串中的指定内容。
#include <QCoreApplication> //Qt提供一个事件循环
#include <QDebug> //输出流
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString sFish = "鱼的记忆是三秒钟的故事";
sFish.replace("三","七");
qDebug()<<sFish;
return a.exec();
}
0008 "QString::startsWith()"函数
QString::startsWith()函数:判断一个字符串是否以某个字符串开头。
Qt::CaseInsensitive代表大小写不敏感;
Qt::CaseSensitive表示大小写敏感;
对应关系函数:QString::endsWith()。
#include <QCoreApplication> //Qt提供一个事件循环
#include <QDebug> //输出流
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString strtemp = "How are you?";
qDebug()<<strtemp.startsWith("How",Qt::CaseSensitive); //true
qDebug()<<strtemp.startsWith("hoW",Qt::CaseSensitive); //False
qDebug()<<strtemp.startsWith("hoW",Qt::CaseInsensitive); //true
qDebug()<<strtemp.startsWith("are",Qt::CaseSensitive); //False
return a.exec();
}
0009 "QString::contains()"函数
判断指定字符串是否在某字符串中出现过。
#include <QCoreApplication> //Qt提供一个事件循环
#include <QDebug> //输出流
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString strtemp = "How are you?";
qDebug()<<strtemp.contains("are",Qt::CaseSensitive); //true
qDebug()<<strtemp.contains("hoWs",Qt::CaseInsensitive); //False
return a.exec();
}
0010 "QString::toInt()"函数
类似还有
"QString::Double()"函数
"QString::Float()"函数
"QString::toLong()"函数
#include <QCoreApplication> //Qt提供一个事件循环
#include <QDebug> //输出流
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString str= "25";
bool isloop;
int hex = str.toInt(&isloop,16);
qDebug()<<"isloop="<<isloop<<","<<"hex="<<hex<<Qt::endl;
return a.exec();
}
0011 "QString::Compare()"函数
#include <QCoreApplication> //Qt提供一个事件循环
#include <QDebug> //输出流
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int a1 = QString::compare("abcd","ABCD",Qt::CaseInsensitive); //大小写不敏感
int b1 = QString::compare("about","Cat",Qt::CaseSensitive);
int c1 = QString::compare("abcd","Cat",Qt::CaseInsensitive);
cout<<"a1="<<a1<<","<<"b1="<<b1<<","<<"c1="<<c1<<endl;
return a.exec();
}
0012 Qt将QString转换成ASCII码
#include <QCoreApplication> //Qt提供一个事件循环
#include <QDebug> //输出流
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString str = "ABC abc";
QByteArray bytes = str.toUtf8();
for (int i=0;i<str.size();i++)
qDebug()<<int(bytes.at(i));
return a.exec();
}
002 Qt常见基本数据类型(定义在#include<QtGlobal>中)
0001 数据类型
类型名称 | 注释 | 备注 |
qint8 | signed char | 8位有符号数据类型 |
qint16 | signed short | 16位有符号数据类型 |
qint32 | signed short | 32位有符号数据类型 |
qint64 | long long int或(_int64) | 64位有符号数据类型,Windows中定义为_int64 |
qintptr | qint32或qitn64 | 指针类型 根据系统类型不同而不同,32位系统为qint32,64位系统为qint64 |
qlonglong | long long int或(_int64) | Windows中定义为_int64 |
qptrdiff | qint32或qint64 | 根据系统类型不同而不同,32位系统为qint32、64位系统为qint64 |
qreal | double或float | 除非配置了-qreal float选项,否则默认为double |
quint8 | unsigned char | 无符号8位数据类型 |
quint16 | unsigned short | 无符号16位数据类型 |
quint32 | unsigned int | 无符号32位数据类型 |
quint64 | unsigned long long int 或(unsigned _int64) | 无符号64比特数据类型,Windows中定义为unsigned_int64 |
quintptr | quint32或quint64 | 根据系统类型不同而不同,32位系统为quint32、64位系统为quint64 |
qulonglong | unsigned long long int或(unsigned _int64) | Windows中定义为_int64 |
unchar | unsigned char | 无符号字符类型 |
uint | unsigned int | 无符号整型 |
ulong | unsigned long | 无符号长整型 |
ushort | unsigned short | 无符号短整型 |
0002 QDateTime&QByteArray
#include <QCoreApplication> //Qt提供一个事件循环
#include <QDebug> //输出流
#include <iostream>
#include <QDateTime>
using namespace std;
int main(int argc, char *argv[])
{
QDateTime dt;
QString strDT = dt.currentDateTime().toString("yyyy-MM--dd hh:mm:ss"); //获取当前时间并转换格式
qDebug()<<strDT<<Qt::endl;
QByteArray a1("Qt Creator Hello World.");
QByteArray b1=a1.toLower(); //将字符串大写字母转小写,小写不变
qDebug()<<b1<<Qt::endl;
QByteArray c1=a1.toUpper(); //将字符串大写字母转大写,大写不变
qDebug()<<c1<<Qt::endl;
return a.exec();
}
06 QMap&QHash&QVector
001 QMap类
QMap<Key,T>提供一个从类型key的键到类型为T的值的映射。通常,QMap存储的数据形式是一个键对应一个值,并且按照键key的顺序依次存储数据。为了能都支持一键多值的情况,QMap提供QMap<key,T>::insertMulti()和QMap<key,T>::values()函数。QMultiMap类来实例化一个QMap对象。
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//QMap类
//1.创建QMap类实例,第一个参数为QString类型的键,第二个参数为int类型的值
QMap<QString,int> qmap;
//插入数据信息,有两大方式进行操作
qmap["Chinese"]=119;
qmap["English"]=120;
qmap.insert("Math",115);
qmap.insert("Physics",99);
qmap.insert("Chemistry",100);
qDebug()<<qmap<<Qt::endl;
//删除数据信息key键
qmap.remove("Chemistry");
qDebug()<<qmap<<Qt::endl;
//遍历qmap类的实例:数据信息
//1:迭代器
QMapIterator<QString,int> itr(qmap);
while(itr.hasNext())
{
itr.next();
qDebug()<<itr.key()<<":"<<itr.value();
}
//2:STL类型的迭代
QMap<QString,int>::const_iterator stritr = qmap.constBegin();
while(stritr != qmap.constEnd())
{
qDebug()<<stritr.key()<<":"<<stritr.value();
stritr++;
}
//key键/T键 -->查找
qDebug()<<Qt::endl;
qDebug()<<"key-->T:"<<qmap.value("Math");
qDebug()<<"T-->key:"<<qmap.key(99)<<Qt::endl;
//修改键值
//一个键对应一个值,再次调用insert()将覆盖之前的函数
qmap.insert("Math",118);
qDebug()<<qmap.value("Math");
//查询是否包含某一个键
qDebug()<<"result="<<qmap.contains("Chinese");
qDebug()<<"result="<<qmap.contains("Chemistry");
//输出所有QMap实例化:Key键和T键值
qDebug()<<Qt::endl;
QList<QString> aKeys = qmap.keys();
qDebug()<<aKeys;
QList<int> aValues = qmap.values();
qDebug()<<aValues;
//一个键对应多个值
//直接使用QMultiMap类来实例化一个QMap对象
qDebug()<<endl;
QMultiMap<QString,QString> mulmap;
mulmap.insert("strudent","no");
mulmap.insert("strudent","name");
mulmap.insert("strudent","sex");
mulmap.insert("strudent","age");
mulmap.insert("strudent","high");
mulmap.insert("strudent","weight");
qDebug()<<mulmap; //从输出结果可以看出mulmap仍然是一个QMap对象
return a.exec();
}
002 QHash类
QHash<Key,T>具有与QMap几乎完全相同的API。QHash维护者一张哈希表(Hash Table),哈希表的大小与QHash的数据项的数目相适应。
QHash以任意的顺序组织它的数据。当存储数据的顺序无关紧要时,建议使用QHash作为存放数据的容器。
QMap与QHash区别:
(1)QHash与QMap的功能差不多,但QHash的查找速度更快;
(2)QMap是按照键的顺序存储数据,而QHash是任意顺序存储的;
(3)QMap的键必须提供"<"运算符,而QHash的键必须提供"=="运算符和一个名为qHash()的全局散列函数。
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//QHash类
QHash<QString,int> qhash;
qhash["key 1"]=3;
qhash["key 1"]=8;
qhash["key 4"]=4;
qhash["key 2"]=2;
qhash.insert("key 3",30);
QList<QString> list=qhash.keys();
for(int i=0;i<list.length();i++)
qDebug()<<list[i]<<","<<qhash.value(list[i]);
//QHash内部的迭代器QHashIterator类
qDebug()<<Qt::endl;
QHash<QString,int> hash;
hash["key 1"]=33;
hash["key 2"]=44;
hash["key 3"]=55;
hash["key 4"]=66;
hash.insert("key 3",100);
QHash<QString,int>::const_iterator iterator;
for(iterator=hash.begin();iterator!=hash.end();iterator++)
qDebug()<<iterator.key()<<"-->"<<iterator.value();
//查询是否包含某一个键
qDebug()<<"result="<<hash.contains("key 4");
//删除键值
hash.remove("key 4");
for(iterator=hash.begin();iterator!=hash.end();iterator++)
qDebug()<<iterator.key()<<"-->"<<iterator.value();
return a.exec();
}
003 QVector类
QVector<T>在相邻的内存中存储给定数据类型T的一组数值。在一个QVector的前部或者中间位置进行插入操作的速度是很慢的,这是因为这样的操作将导致内存中的大量数据被移动,这是由QVector存储数据的方式决定的。
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//QVector类
//QVector<T>是Qt的一个容器类
QVector<int> qvr;
//第一种赋值方式
qvr<<10;
qvr<<20;
qvr<<30;
qvr<<40;
//第二种赋值方式
qvr.append(50);
qvr.append(60);
qvr.append(70);
qvr.append(80);
qvr.append(100);
qvr.append(90);
qDebug()<<qvr<<Qt::endl;
//求出QVector类容器的实例化:元素个数
qDebug()<<"qvr count="<<qvr.count()<<Qt::endl;
//遍历所有元素
for(int i=0;i<qvr.count();i++)
qDebug()<<qvr[i];
//删除qvr容器里面的元素
qDebug()<<Qt::endl;
qvr.remove(0); //删除第0个元素
for(int i=0;i<qvr.count();i++)
qDebug()<<qvr[i];
qDebug()<<Qt::endl;
qvr.remove(2,3); //从第二个元素开始,删除3个元素
for(int i=0;i<qvr.count();i++)
qDebug()<<qvr[i];
//判断容器是否包含某个元素
qDebug()<<Qt::endl;
qDebug()<<"result:"<<qvr.contains(90)<<Qt::endl;
qDebug()<<"result:"<<qvr.contains(600)<<Qt::endl;
return a.exec();
}
07 QList类&QLinkedList类
001 QList类
对于不同的数据类型,QList<T>采取不同的存储策略,存储策略如下:
(1)如果T是一个指针类型或者指针大小的基本类型(该基本类型占有的字节数和指针类型占有的字节数相同),QList<T>将数值直接存储在它的数组当中。
(2)如果QList<T>是存储对象的指针,则该指针指向实际存储的对象。
#include <QCoreApplication>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//QList类
QList<int> qlist; //初始化一个空的QList<int>列表
for(int i =0;i<10;i++)
qlist.insert(qlist.end(),i+10);
qDebug()<<qlist;
//通过QList<int>::itertor读写迭代器
QList<int>::iterator x;
qDebug()<<Qt::endl;
qDebug()<<"Result1:";
for(x=qlist.begin();x!=qlist.end();x++)
{
qDebug()<<(*x);
*x = (*x)*10+6;
}
//初始化一个QList<int>const_iterator只读迭代器
qDebug()<<Qt::endl;
qDebug()<<"Result1:";
QList<int>::const_iterator qciter;
//输出列表中所有的值
for(qciter =qlist.constBegin();qciter != qlist.constEnd();qciter++)
qDebug()<<*qciter;
//向qlist添加元素
qlist.append(666);
QList<int>::iterator itr1;
qDebug()<<Qt::endl;
qDebug()<<"Result2:";
for(itr1 = qlist.begin();itr1!=qlist.end();itr1++)
qDebug()<<*itr1;
//查找qlist当中的元素
qDebug()<<Qt::endl;
qDebug()<<"Result3:";
qDebug()<<qlist.at(3);
qDebug()<<qlist.contains(77);
qDebug()<<qlist.contains(166);
//修改qlist列表里边中的元素
qDebug()<<Qt::endl;
qDebug()<<"Result4:";
qlist.replace(5,888);
qDebug()<<qlist;
//删除元素
qDebug()<<Qt::endl;
qDebug()<<"Result5:";
qlist.removeAt(0);
qlist.removeFirst();
qlist.removeAt(6);
qDebug()<<qlist;
return a.exec();
}
002 QLinkedList类
Qt6中无法使用QLinkedList类解决办法:
error: Unknown module(s) in QT: core5compat问题解决方法_:-1: error: unknown module(s) in qt: core5compat-CSDN博客
https://blog.csdn.net/weixin_65548587/article/details/132215265Qt6以上版本不能引用头文件QLinkedList和使用链式列表的问题_qt 6 头文件引用-CSDN博客
https://blog.csdn.net/m0_65132134/article/details/137111154
QLinkedList<T>是一个链式列表,它以非连续的内存块保存数据。QLinkedList<T>不能使用下标,只能使用迭代器访问它的数据项。与QList相比,当对一个很大的列表进行插入操作时,QLinkedList具有更高的效率。
QLinkedList类不能通过索引方式访问元素(链表),保存大规模数量数据信息建议使用QLinkedList(插入元素和删除元素速度快、效率高)。
#include <QCoreApplication>
#include <QDebug>
#include <qlinkedlist.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//QLinkedList类
QLinkedList<QString> qAllMonth;
for(int i=1;i<=12;i++)
qAllMonth<<QString("%1%2").arg("Month:").arg(i);
//读写迭代器
qDebug()<<"Result1:";
QLinkedList<QString>::iterator itrw=qAllMonth.begin();
for(;itrw!=qAllMonth.end();itrw++)
qDebug()<<*itrw;
//只读迭代器
qDebug()<<Qt::endl<<"Result2:";
QLinkedList<QString>::const_iterator itr=qAllMonth.constBegin();
for(;itr!=qAllMonth.end();itr++)
qDebug()<<*itr;
return a.exec();
}
0003 STL风格迭代器遍历容器
容器类 | 只读迭代器类 | 读写迭代器类 |
QList<T>,QQueue<T> | QList<T>::const_iterator | QList<T>::iterator |
QLinkedList<T> | QLinkedList<T>::const_iterator | QLinkedList<T>::iterator |
08 QVariant类应用
QVariant 类本质为C++联合(Union)数据类型,它可以保存很多Qt 类型的值,包括QBrush、QColor、QString 等等。也能够存放Qt 的容器类型的值。
QVariant::StringList 是Qt 定义的一个QVariant::type 枚举类型的变量,其他常用的枚举类型变量如下表所示:
变量 | 对的类型 | 变量 | 对象的类型 |
QVariant::Invalid | 无效类型 | QVariant::Time | QTime |
QVariant::Region | QRegion | QVariant::Line | QLine |
QVariant::Bitmap | QBitmap | QVariant::Palette | QPalette |
QVariant::Bool | bool | QVariant::List | QList |
QVariant::Brush | QBrush | QVariant::SizePolicy | QSizePolicy |
QVariant::Size | QSize | QVariant::String | QString |
QVariant::Char | QChar | QVariant::Map | QMap |
QVariant::Color | QColor | QVariant::StringList | QStringList |
QVariant::Cursor | QCursor | QVariant::Point | QPoint |
QVariant::Date | QDate | QVariant::Pen | QPen |
QVariant::DateTime | QDateTime | QVariant::Pixmap | QPixmap |
QVariant::Double | double | QVariant::Rect | QRect |
QVariant::Font | QFont | QVariant::Image | QImage |
QVariant::Icon | QIcon | QVariant::UserType | 用户自定义类型 |
案例:
(1)创建MainWindow项目;
(2)修改"main.cpp"文件;
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
// w.show();
return a.exec();
}
(3)修改"mainwindow.h"文件;
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
//定义学生结构体类型
struct student
{
int iNO;
QString strName;
int score;
};
Q_DECLARE_METATYPE(student)
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
};
#endif // MAINWINDOW_H
(4)修改"mainwindow.cpp"文件
#include "mainwindow.h"
#include <QVariant>
#include <QDebug>
#include <QColor>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QVariant qv1(298);
qDebug()<<"qv1:"<<qv1.toInt();
QVariant qv2("beijing");
qDebug()<<"qv2:"<<qv2.toString();
QMap<QString,QVariant> qmap;
qDebug()<<Qt::endl;
qmap["int"] = 2000;
qmap["double"] = 99.88;
qmap["string"] = "good";
qmap["color"] = QColor(255,255,0); //Qcolor类型
//输出,转换函数来处理
qDebug()<<qmap["int"]<<qmap["int"].toInt();
qDebug()<<qmap["double"]<<qmap["double"].toDouble();
qDebug()<<qmap["string"]<<qmap["string"].toString();
qDebug()<<qmap["color"]<<qmap["color"].value<QColor>();
//创建字符串列表:QStringList
qDebug()<<Qt::endl;
QStringList qsl;
qsl<<"A"<<"B"<<"C"<<"D"<<"E"<<"F";
QVariant qvsl(qsl); //将列表储存在一个QVariant变量
if(qvsl.type()==QVariant::StringList)
{
QStringList qlist=qvsl.toStringList();
for(int i=0;i<qlist.size();i++)
{
qDebug()<<qlist.at(i); //输出列表数据信息
}
}
//结构体类型和QVariant类配合使用
qDebug()<<Qt::endl;
student stu;
stu.iNO = 202407;
stu.strName = "sunny";
stu.score = 715;
//使用静态方法进行保存
QVariant qstu = QVariant::fromValue(stu);
if(qstu.canConvert<student>()) //判断是否可以转换操作
{
student temp=qstu.value<student>(); //获取数据
student qtemp = qvariant_cast<student>(qstu); //获取数据
qDebug()<<"student:iNo="<<temp.iNO<<",strName="<<temp.strName<<",score="<<temp.score;
qDebug()<<"student:iNo="<<qtemp.iNO<<",strName="<<qtemp.strName<<",score="<<qtemp.score;
}
}
MainWindow::~MainWindow()
{
}
09 常用算法及正则表达式
001 常用算法
(1)double c = qAbs(a):数qAbs()返回double型数值a的绝对值;
(2)double max = qMax(b,c):函数qMax()返回两个数值中的最大值;
(3)int bn = qRound(b):返回一个与浮点数最接近的整数值(四舍五入);
(4)int cn = qSwap(bn,cn):交换两数的值;
案例:
(1)创建widget项目;
(2)修改"widget.cpp"文件;
#include "widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
double x = -98.654,y=25.98;
double result1 = qAbs(x); //取绝对值
qDebug()<<"x="<<result1;
double maxresult = qMax(x,y); //取最大值
qDebug()<<"maxresult"<<maxresult;
int result2 = qRound(y); //四舍五入
qDebug()<<"result2="<<result2;
int result3 = qRound(x); //四舍五入
qDebug()<<"result3="<<result3;
qSwap(x,y); //交换两数的值
qDebug()<<x<<","<<y<<Qt::endl;
}
Widget::~Widget()
{
}
002 正则表达式
正则表达式,又称规则表达式(Regular Expression,在代码中常简写为regex、regexp或RE),是一种文本模式,包括普通字符(例如,a到z之间的字母)和特殊字符(称为“元字符”)。正则表达式使用单个字符串来描述、匹配一系列匹配某个语法规则的字符串,通常用来检索,替换那些符合某个模式(规则)的文本。正则表达式描述一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等等。
正则表达式由表达式(expressions)、量词(quantifiers)、断言(assertions)组成。
(1)最简单的表达式是一个字符。字符集可以使用表达式如"[AEIOU]",表示匹配所有的大写元音字母;使用"[^AEIOU]",表示匹配所有非元音字母,即辅音字母;连续的字符集可以使用表达式如"[a-z]",表示匹配所有的小写英文字母。
(2)量词说明表达式出现的次数,如"x[1,2]"表示"x"可以至少有一个,至多有两个。
正则表达式的量词:
量词 | 含义 | 量词 | 含义 |
E? | 匹配0次或1次 | E[n,] | 至少匹配n次 |
E+ | 匹配1次或多次 | E[,m] | 最多匹配m次 |
E* | 匹配0次或多次 | E[n,m] | 至少匹配n次,最多匹配m次 |
E[n] | 匹配n次 |
正则表达式的断言:
符号 | 含义 | 符号 | 含义 |
^ | 表示在字符串开头进行匹配 | \B | 非单词边界 |
$ | 表示在字符串结尾进行匹配 | (?=E) | 表示表达式后紧随E才匹配 |
\b | 单词边界 | (?!E) | 表示表达式后不跟随E才匹配 |
案例:
(1)创建mainwidow项目;
(2)修改"mainwindow.cpp"文件;
#include "mainwindow.h"
#include <QDebug>
#include <regex>
#include <QString>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
/*
* 通过正则表达式匹配:手机号码
* 11位数字,其中各段有不同的编码方式
* 前3位:网络识别号(中国移动、中国1联通、中国电信)
* 后面第8位至11位为用户号码
* 中国移动:134 159 158 188
* 中国联通:130 133 189 156
* 相当于1开头,第2位3 5 8,共计11位
*/
QString qMobileNumber = "19954654857";
std::regex reg("^1(3|5|8)\\d{9}$");
std::string UserTelIdString = qMobileNumber.toStdString();
qDebug()<<"Phone Number:"<<qMobileNumber;
//进行匹配
bool bResult = std::regex_match(UserTelIdString,reg);
if(!bResult)
{
qDebug()<<"MobileNumber"<<"-->Error mobile phone number.";
}
else
{
qDebug()<<qMobileNumber<<"-->Right mobile phone number.";
}
}
MainWindow::~MainWindow()
{
}
推荐课程: