Qt --- 基本类

2023-10-30

位置和尺寸

在QT中我们常见的 点, 线, 尺寸, 矩形 都被进行了封装, 下面依次为大家介绍相关的类

QPoint

QPoint类封装了我们常用用到的坐标点 (x, y), 常用的 API如下:

void QPoint::setX(int x);
void QPoint::setY(int y);

int QPoint::x() const;    //只读
int &QPoint::rx();        //返回引用 rx()=20

int QPoint::y() const;
int &QPoint::ry();

//如果x和y坐标都为0则返回true,否则返回false
bool isNull() const

//返回x()和y()的绝对值之和,传统上称为从原点到该点的向量的“曼哈顿长度”--->两条直角边构成的距离
//(p1-p2).manhattanLength();   
int manhattanLength() const    

//返回一个交换了x和y坐标的点:   QPoint{1, 2}.transposed() // {2, 1}  
QPoint transposed() const    
    
// 直接通过坐标对象进行算术运算: 加减乘除 对坐标的缩放操作
QPoint &QPoint::operator*=(float factor);
QPoint &QPoint::operator*=(double factor);
QPoint &QPoint::operator*=(int factor);
QPoint &QPoint::operator+=(const QPoint &point);
QPoint &QPoint::operator-=(const QPoint &point);
QPoint &QPoint::operator/=(qreal divisor);
...
//测试代码
#include<QPoint>
void testPoint();
void testPoint()
{
    //构造坐标点
    QPoint pos(5,4);
    //修改坐标 10 4
    pos.setX(10);
    //获取坐标
    qDebug()<<pos<<pos.x()<<pos.y();
    //修改坐标 5 5
    pos.rx()=5;
    pos.ry()=5;
    qDebug()<<pos<<pos.x()<<pos.y();
    //获取曼哈顿长度(相对于坐标原点)
    qDebug()<<pos.manhattanLength();    //5+5==10
    //下面是两个点的曼哈顿距离--->两个点相减得到两点距离再求曼哈顿距离
    qDwbug()<<QPoint(1,1)-QPoint(2,2).manhattanLength();
    //交换x和y
    qDebug()<<QPoint(2,3).transposed();
}

/*输出*/
QPoint(10,4) 10 4
QPoint(5,5) 5 5
10
2
QPoint(3,2) 

QLine

QLine是一个直线类, 封装了两个坐标点 (两点确定一条直线)

常用API如下:

// 设置直线的起点坐标
void setP1(const QPoint &p1);
// 设置直线的终点坐标
void setP2(const QPoint &p2);

void setPoints(const QPoint &p1, const QPoint &p2);    //两点确定一条线段
void setLine(int x1, int y1, int x2, int y2);


QPoint p1() const;		// 返回直线的起始点坐标
QPoint p2() const;		// 返回直线的终点坐标
QPoint center() const;	// 返回值直线的中心点坐标, (p1() + p2()) / 2	


int x1() const;		    // 返回值直线起点的 x 坐标
int y1() const;		    // 返回值直线起点的 y 坐标
int x2() const;		    // 返回值直线终点的 x 坐标
int y2() const;		    // 返回值直线终点的 y 坐标

int dx() const			//返回直线向量的水平分量  
int dy() const			//返回直线向量的垂直分量  

// 用给定的坐标点平移这条直线
void translate(const QPoint &offset);
void translate(int dx, int dy);
// 用给定的坐标点平移这条直线, 返回平移之后的坐标点(不会改变这条线的坐标)
QLine translated(const QPoint &offset) const;
QLine translated(int dx, int dy) const;

// 直线对象进行比较
bool operator!=(const QLine &line) const;
bool operator==(const QLine &line) const;
#include<QLine>
void testLine()
{
    //线段
    QLine line(2,3,4,5);
    //设置直线的起点坐标
    line.setP1(QPoint(10,10));   //QLine(QPoint(10,10),QPoint(4,5))
    //设置坐标
    line.setLine(5,5,9,9);
    //平移线段
    line.translate(1,2);
    qDebug()<<line;

    line.translate(3,3);
    qDebug()<<line;
    qDebug()<<line.translated(3,3);
}
/*输出*/

Qline(QPoint(5,5),QPoint(9,9)) 
Qline(QPoint(6,7),QPoint(10,11))  //有d不会对自身的线段进行操作 返回一个临时对象
Qline(QPoint(9,10),QPoint(13,14)) //用qDebug()<<line.translated(3,3)输出

QSize

在QT中QSize类用来形容长度和宽度, 常用的API如下:

void setWidth(int width)
void setHeight(int height);

int width() const;		// 得到宽度
int &rwidth();			// 得到宽度的引用
int height() const;		// 得到高度
int &rheight();			// 得到高度的引用

void transpose();			// 交换高度和宽度的值
QSize transposed() const;	// 交换高度和宽度的值, 返回交换之后的尺寸信息

//返回一个大小,宽为当前大小与other的最小值,高为当前大小与other的最小值
QSize boundedTo(const QSize& oterSize)
//返回一个大小,宽为当前大小与other的最大值,高为当前大小与other的最大值    
QSize expandedTo(const QSize &otherSize) const    
    
/*
根据指定的模式,按给定的宽度和高度缩放矩形:  
	如果mode为Qt::IgnoreAspectRatio,则大小设置为(width, height)。  
	如果mode为Qt::KeepAspectRatio,当前大小将在内部缩放到一个尽可能大的矩形(宽度,高度),保持高宽比。  
	如果mode是Qt::KeepAspectRatioByExpanding,当前大小被缩放到一个矩形,尽可能小的外部(宽度,高度),保持长宽比。  
*/
void scale(int width, int height, Qt::AspectRatioMode mode)
void scale(const QSize &size, Qt::AspectRatioMode mode)
QSize scaled(int width, int height, Qt::AspectRatioMode mode) const
QSize scaled(const QSize &s, Qt::AspectRatioMode mode) const
    

// 进行算法运算: 加减乘除
QSize &operator*=(qreal factor);
QSize &operator+=(const QSize &size);
QSize &operator-=(const QSize &size);
QSize &operator/=(qreal divisor);

#include<QSize>
void testSize()
{
    QSize size(640,480);
    //设置宽度和高度
    size.setWidth(1920);
    size.setHeight(1080);
    size.width();
    size.heigth();
    qDebug()<<size;
    //大小缩放
    size.scale(640,480,Qt::IgnoreAspectRatio);            //忽略宽高比
    //保持宽高比
    size.scale(640,480,Qt::KeepAspectRatio);              //保持宽高比
    size.scale(640,480,Qt::KeepAspectRatioByExpanding);   //保持宽高比拓展
    qDebug()<<size;
    //把两个Size的最小宽度和高度拿出来构造成一个新的size返回
    qDebug()<<QSize(640,480).boundedTo(QSize(320,640));
}
/*输出*/

QSize(1920,1080)

QSize(640,480)                                            //忽略宽高比
QSize(640,360)                                            //保持宽高比 短边和长边的区别
QSize(853,480)                                            //保持宽高比

QSize(320,480)

QRect 

在Qt中使用 QRect类来描述一个矩形, 常用的API如下:

// 构造一个空对象
QRect::QRect();
// 基于左上角坐标, 和右下角坐标构造一个矩形对象
QRect::QRect(const QPoint &topLeft, const QPoint &bottomRight);
// 基于左上角坐标, 和 宽度, 高度构造一个矩形对象
QRect::QRect(const QPoint &topLeft, const QSize &size);
// 通过 左上角坐标(x, y), 和 矩形尺寸(width, height) 构造一个矩形对象
QRect::QRect(int x, int y, int width, int height);

// 设置矩形的尺寸信息, 左上角坐标不变
void QRect::setSize(const QSize &size);
// 设置矩形左上角坐标为(x,y), 大小为(width, height)
void QRect::setRect(int x, int y, int width, int height);
// 设置矩形宽度
void QRect::setWidth(int width);
// 设置矩形高度
void QRect::setHeight(int height);

// 返回值矩形左上角坐标
QPoint QRect::topLeft() const;
// 返回矩形右上角坐标
// 该坐标点值为: QPoint(left() + width() -1, top())
QPoint QRect::topRight() const;
// 返回矩形左下角坐标
// 该坐标点值为: QPoint(left(), top() + height() - 1)
QPoint QRect::bottomLeft() const;
// 返回矩形右下角坐标
// 该坐标点值为: QPoint(left() + width() -1, top() + height() - 1)
QPoint QRect::bottomRight() const;
// 返回矩形中心点坐标
QPoint QRect::center() const;

// 返回矩形上边缘y轴坐标
int QRect::top() const;
int QRect::y() const;
// 返回值矩形下边缘y轴坐标
int QRect::bottom() const;
// 返回矩形左边缘 x轴坐标
int QRect::x() const;
int QRect::left() const;
// 返回矩形右边缘x轴坐标
int QRect::right() const;

// 返回矩形的高度
int QRect::width() const;
// 返回矩形的宽度
int QRect::height() const;
// 返回矩形的尺寸信息
QSize QRect::size() const;

//调整矩形的尺寸 (左上角和右下角坐标偏移量)
void QRect::adjust(int dx1, int dy1, int dx2, int dy2)
QRect QRect::adjusted(int dx1, int dy1, int dx2, int dy2) const    

//测试代码
#include<QRect>
void testRect()
{
    //构造一个矩形
    QRect rect(5,5,250,250);
    //输出左上角的坐标
    qDebug()<<rect.topLeft();
    //输出右下角的坐标
    qDebug()<<rect.bottomRight();
    qDebug()<<rect.bottomRight()+QPoint(1,1); //正常获取像素需要+1
    qDebug()<<rect;
   
    rect.adjust(1,1,-1,-1);                   //左上角都+1 右下角都-1
    //判断矩形是否包含某个点
    if(rect.contains(QPoint(6,6));            //(6,6)刚好在矩形上面
    {
        qDebug()<<"is in";
    }
    //判断矩形是否包含某个点,(6,6)刚好在矩形上面 bool类型的参数:是否严格判断:必须在里面|在上面的情况不算 
    if(rect.contains(QPoint(6,6),true))
    {
        qDebug()<<"is in";
    }
}
/*输出*/

QRect(5,5);
QRect(254,254);     //坐标系统是浮点型的,是在1的中间绘制线,前后各少了一半,合起来刚好少了一个像素 QRect(255,255); 
QRect(5,5,250*250)
QRect(6,6,248*248)  //一来一去两个像素

is in
...

 日期和时间

 QDate

// 构造函数
QDate::QDate();
QDate::QDate(int y, int m, int d);    //年 月 日

// 公共成员函数
// 重新设置日期对象中的日期
bool QDate::setDate(int year, int month, int day);
// 给日期对象添加 ndays 天
QDate QDate::addDays(qint64 ndays) const;
// 给日期对象添加 nmonths 月
QDate QDate::addMonths(int nmonths) const;
// 给日期对象添加 nyears 月
QDate QDate::addYears(int nyears) const;

// 得到日期对象中的年/月/日
int QDate::year() const;
int QDate::month() const;
int QDate::day() const;
void QDate::getDate(int *year, int *month, int *day) const;
 
/*日期对象格式化
    d 		- 	没有前导零的日子 (1 to 31)  
    dd		-	前导为0的日子   (01 to 31)  
    ddd		-	显示(缩写) 周一、周二、周三、周四、周五、周六、周日		
    dddd	- 	显示(完整) 星期一、星期二、星期三、星期四、星期五、星期六、星期日
    
    M		-	没有前导零的月份(1到12)  在年月日中只有月份是大写 小写m用来表示其他东西
    MM		-	前导零的月份(01到12)  
    MMM		-	缩写 1月、2月、3月...         
    MMMM	-	完整 一月、二月、三月...
    
    yy		-	两个数字的年 (00 to 99)
    yyyy	-	以四位数表示的年份
*/
QString QDate::toString(const QString &format) const;

// 操作符重载 ==> 日期比较
bool QDate::operator!=(const QDate &d) const;
bool QDate::operator<(const QDate &d) const;
bool QDate::operator<=(const QDate &d) const;
bool QDate::operator==(const QDate &d) const;
bool QDate::operator>(const QDate &d) const;
bool QDate::operator>=(const QDate &d) const;

// 静态函数 -> 得到本地的当前日期
[static] QDate QDate::currentDate();
//测试代码
#include<QDate>
void testDate()
{
    //构造一个日期对象
    QDate date(2021,3,4);
    qDebug()<<date;
    //获取当前的日期
    QDate curDate = QData::currentDate();
    qDebug()<<curDate;
    //获取年,月,日
    qDebug()<<curDate.year()<<curDate.month()<<curDate.day();
    //获取日期对应的星期--->一周的的第几天
    qDebug()<<curDate.dayOfWeek();
    //把日期转成字符串
    QString dateStr = date.toString();
    QString dateStr = date.toString(Qt::DateFormat::ISODate);
    QString dateStr = date.toString(Qt::DateFormat::LocalDate);
    dateStr = date.toString("今天是yy--MM-dd");
    dateStr = date.toString("今天是yy--MMMM-dd");
    qDebug()<<dateStr;
}
/*输出*/
QDate("2021-03-04")
QDate("2022-03-04")
2022 3 4
5
"周四 3月 4 2021"
"2021-03-04"
"2021/3/4"
"今天是2021-03-04"
"今天是2021-三月-04"

 QTime

// 构造函数
QTime::QTime();    //时 分 秒 毫秒
/*
    h 			==> must be in the range 0 to 23
    m and s 	==> must be in the range 0 to 59
    ms 			==> must be in the range 0 to 999
*/ 
QTime::QTime(int h, int m, int s = 0, int ms = 0);

// 公共成员函数
// Returns true if the set time is valid; otherwise returns false.
bool QTime::setHMS(int h, int m, int s, int ms = 0);
QTime QTime::addSecs(int s) const;
QTime QTime::addMSecs(int ms) const;

// 示例代码
  QTime n(14, 0, 0);                // n == 14:00:00
  QTime t;
  t = n.addSecs(70);                // t == 14:01:10
  t = n.addSecs(-70);               // t == 13:58:50
  t = n.addSecs(10 * 60 * 60 + 5);  // t == 00:00:05
  t = n.addSecs(-15 * 60 * 60);     // t == 23:00:00

// 从时间对象中取出 时/分/秒/毫秒
// Returns the hour part (0 to 23) of the time. Returns -1 if the time is invalid.
int QTime::hour() const;
// Returns the minute part (0 to 59) of the time. Returns -1 if the time is invalid.
int QTime::minute() const;
// Returns the second part (0 to 59) of the time. Returns -1 if the time is invalid.
int QTime::second() const;
// Returns the millisecond part (0 to 999) of the time. Returns -1 if the time is invalid.
int QTime::msec() const;


// 时间格式化
/*
	-- 时   如果是AM/PM显示,0 ~ 23或1 ~ 12
    h	==>	The hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
    hh	==>	The hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)\
            0到23,即使有AM/PM显示
    H	==>	The hour without a leading zero (0 to 23, even with AM/PM display)
    HH	==>	The hour with a leading zero (00 to 23, even with AM/PM display)
    -- 分
    m	==>	The minute without a leading zero (0 to 59)
    mm	==>	The minute with a leading zero (00 to 59)
    -- 秒
    s	==>	The whole second, without any leading zero (0 to 59)
    ss	==>	The whole second, with a leading zero where applicable (00 to 59)
    -- 毫秒
	zzz	==>	The fractional part of the second, to millisecond precision, 
			including trailing zeroes where applicable (000 to 999).
	-- 上午或者下午
    AP or A		==>		使用AM/PM(大写) 描述上下午, 中文系统显示汉字
    ap or a		==>		使用am/pm(小写) 描述上下午, 中文系统显示汉字
*/
QString QTime::toString(const QString &format) const;


// 操作符重载 ==> 时间比较
bool QTime::operator!=(const QTime &t) const;
bool QTime::operator<(const QTime &t) const;
bool QTime::operator<=(const QTime &t) const;
bool QTime::operator==(const QTime &t) const;
bool QTime::operator>(const QTime &t) const;
bool QTime::operator>=(const QTime &t) const;

// 静态函数 -> 得到当前时间
[static] QTime QTime::currentTime();
//测试代码
#include<Qtime>
void testTime()
{
    //获取当前时间
    QTime curTime = QTime::currentTime();
    qDebug()<<curTime;

    //获取时,分,秒,毫秒
    qDebug()<<curTime.hour()<<curTime.minute()<<curTime.second()<<curTime.msec();

    //把时间转换为字符串
    QString timeStr = curTime.toString("AP hh:mm:ss:zzz");

    qDebug()<<timeStr;
    //从字符串获取时间
    qDebug()<<QTime::fromString(timeStr,"AP hh:mm:ss:zzz");    //使用的是自定义格式需要把格式加在后面 | 如果使用标准方式就不用写后面的参数

}
/*输出*/

QTime("21:31:08.716")
21 31 08 716

"下午21:31:08:716"
QTime("21:31:08.716")

 经时计时器

 QTime 的经时计时器已经过时了,推荐使用 QElapsedTimer

//QTime已废弃的函数
// 开始计时
void QTime::start();
// 计时结束
int QTime::elapsed() const;
// 重新计时
int QTime::restart();

// 推荐使用的API函数
// QElapsedTimer 类
void QElapsedTimer::start();
qint64 QElapsedTimer::restart();
qint64 QElapsedTimer::elapsed() const;

 主要的使用方法就是测量一个操作耗时多久,例子如下:

#include<QElapsedTimer>
QElapsedTimer elapse;
elapse.start();
 //经过计时器可以用来计算某段代码,执行用了多长时间
for(int i = 0;i<1000000;i++);

elapse.restart();                             //重新开始计时
qDebug()<<elapse.elapsed()<<endl;             //0

void testElapsed()
{
    QTime time;
    time.start();                            //启动计时器
    for(int i = 0;i<1000000;i++)
    {
        ;
    }
    qDebug()<<"总共耗时: "<<time.elapsed();  //从启动到调用函数经过了多长时间
    
}
/*输出*/

总共耗时: 1(毫秒)

 QDateTime

// 构造函数
QDateTime::QDateTime();      //既有日期也有时间
QDateTime::QDateTime(const QDate &date, const QTime &time, Qt::TimeSpec spec = Qt::LocalTime);

// 公共成员函数
// 设置日期
void QDateTime::setDate(const QDate &date);
// 设置时间
void QDateTime::setTime(const QTime &time);
// 给当前日期对象追加 年/月/日/秒/毫秒, 参数可以是负数
QDateTime QDateTime::addYears(int nyears) const;
QDateTime QDateTime::addMonths(int nmonths) const;
QDateTime QDateTime::addDays(qint64 ndays) const;
QDateTime QDateTime::addSecs(qint64 s) const;
QDateTime QDateTime::addMSecs(qint64 msecs) const;

// 得到对象中的日期
QDate QDateTime::date() const;
// 得到对象中的时间
QTime QDateTime::time() const;

// 日期和时间格式, 格式字符参考QDate 和 QTime 类的 toString() 函数
QString QDateTime::toString(const QString &format) const;


// 操作符重载 ==> 日期时间对象的比较
bool QDateTime::operator!=(const QDateTime &other) const;
bool QDateTime::operator<(const QDateTime &other) const;
bool QDateTime::operator<=(const QDateTime &other) const;
bool QDateTime::operator==(const QDateTime &other) const;
bool QDateTime::operator>(const QDateTime &other) const;
bool QDateTime::operator>=(const QDateTime &other) const;

// 静态函数
// 得到当前时区的日期和时间(本地设置的时区对应的日期和时间)
[static] QDateTime QDateTime::currentDateTime();
#include<QDateTime>
void testDateTime()
{
    //获取当前时间
    QDateTime dateTime = QDateTime::currentDateTime();
    qDebug()<<dateTime;
    //获取日期和时间
    qDebug()<<dateTime.date()<<dateTiem.Time();
    //把dateTime转换为字符串 格式可以自己决定
    qDebug()<<dateTime().toString("yyyy/MM/dd [hh:mm:ss:zz] ap");

}
/*输出*/

QDateTime(2022-03-04 21:46:37.922 中国标准时间 Qt::LocalTime)
QDate("2022-03-04") QTime("21:46:37.922")
"2022/03/04 [21:46:37.922] 下午"

Qt 中容器遍历的方式

container

Qt中提供了一组通用的基于模板的容器类(container class)。可以用来存储指定的项(items),与STL(C++标准模板库)相比,Qt中的容器更轻量,更安全,功能更强大。

  • 序列式容器

    • QList

    • QLinkedList

    • QVector

    • QStack

    • QQueue

    对于大多数应用程序,QList是最好的类型。虽然它是作为数组列表实现的,但是它提供了非常快的前置和追加。如果你真的需要一个链表,使用QLinkedList;如果您希望您的项目占用连续的内存位置,请使用QVector。QStack和QQueue是提供LIFO和FIFO语义的便利类。

  • 关联式容器

    • QMap

    • QMultiMap

    • QHash

    • QMultiHash

    • QSet

    “multi”容器方便地支持与单个键相关联的多个值。“hash”容器通过使用哈希函数而不是对排序集进行二进制搜索,从而提供更快的查找。

  • 作为特殊情况,QCache和QContiguousCache类在有限的缓存存储中提供了对象的高效散列查找。

遍历容器

Qt提供了两种遍历容器的风格:

Java风格 的迭代器和 STL风格 的迭代器。java风格的迭代器更容易使用并提供高级功能,而STL风格的迭代器稍微更高效,可以与Qt和STL的通用算法一起使用

//测试代码
#include<QList>
void testIterator()
{
    QList<int> list;
    //通过初始化参数列表添加数据  
    QList<int> list = {1,2,3,4,5};
    //通过流的方式添加数据
    list<<6<<7<<8<<9;     
    //通过函数添加数据
    list.append(88);   
    list.prepend(11);
    //在2前面的位置添加44
    list.insert(2,44);   
    //遍历
    //java风格         
    QListIterator<int> it(list);
    while (it.hasNext())            //有下一个就获取下一个
    {
        std::out<<it.next()<<" ";
    }
    //STL风格
    for(/*QList<int>::const_iterator*/auto  it = list.constBegin(),it!=constEnd();it++)
    {
        std::cout<<*it<<" ";
    }
    //c++11 给我们提供了一个基于范围的for循环,更简单-->装的是什么类型就定义什么类型,让值到list中去拿 并输出
    for(auto/*int*/ val : list)
    {
        std::cout<<val<<" ";
    }
}

/*输出*/
11 1 44 2 3 4 5 6 7 8 9 88
11 1 44 2 3 4 5 6 7 8 9 88
11 1 44 2 3 4 5 6 7 8 9 88

序列式容器

QList

QList模板提供了一个列表,实际上是一个指针数组,当项目数小于1000时,可以实现快速的插入删除操作

QList<T> 是 Qt 的通用容器类之一。它将项目存储在一个列表中,该列表提供基于索引的快速访问和基于索引的插入和删除。 QList<T>、QLinkedList<T> 和 QVector<T> 提供类似的 API 和功能。它们通常可以互换,但会产生性能后果。

使用概述:

  • QVector 应该是您的默认首选。 QVector<T> 通常会比 QList<T> 提供更好的性能,因为 QVector<T> 总是将其项按顺序存储在内存中,其中 QList<T> 将在堆上分配它的项,除非 sizeof(T) <= sizeof(void *) 并且 T 已使用 Q_DECLARE_TYPEINFO 声明为 Q_MOVABLE_TYPE 或 Q_PRIMITIVE_TYPE。

  • 然而,QList 在整个 Qt API 被大量使用,用于传递参数和返回值。 使用 QList可以很方便的与这些 API 进行交互。

  • 如果您需要一个真正的链表,它保证常量时间内插入列表,并且使用迭代器指向项而不是索引,那么请使用QLinkedList。

公有函数

  • 添加数据

//支持流插入
QList<int>()<<1<<2<<3<<4<<5;

void append(const T &value)
void append(const QList<T> &value)
 
void insert(int i, const T &value)
QList::iterator insert(QList::iterator before, const T &value)

void prepend(const T &value)
void push_back(const T &value)
void push_front(const T &value)
  • 获取数据

T &back()
const T &back() const  

T &first()
const T &first() const
T &front()
const T &front() const 

T &last()
const T &last() const 

const T &constFirst() const
const T &constLast() const

//返回下标为i的元素,如果下标i不合法,则返回defaultValue
T value(int i) const
T value(int i, const T &defaultValue) const  
    
const T &at(int i) const
T &operator[](int i)
const T &operator[](int i) const
//返回从位置pos开始的子列表。如果length为-1(默认),则包含pos中的所有元素; 
QList<T> mid(int pos, int length = -1) const
  • 删除数据

void clear()
    
QList::iterator erase(QList::iterator pos)
QList::iterator erase(QList::iterator begin, QList::iterator end)   

void pop_back()
void pop_front()
//删除元素   
int removeAll(const T &value)
bool removeOne(const T &value)
void removeAt(int i)
void removeFirst()
void removeLast()
//删除元素并返回它,如果不使用返回值,removeAt()会更高效 
T takeAt(int i)
T takeFirst()
T takeLast()
  • 查找/替换

//返回value在列表中第一次出现的索引位置,从索引位置from向前搜索。 如果没有匹配的项,则返回-1。  
int indexOf(const T &value, int from = 0) const
//返回value在列表中最后一次出现的索引位置,从索引位置from反向搜索。如果from是-1(默认值),则搜索从最后一项开始。如果没有匹配的项,则返回-1。     
int lastIndexOf(const T &value, int from = -1) const
//将索引位置为i的项替换为value
void replace(int i, const T &value)
//如果列表中包含值的出现,则返回true; 否则返回false。 该函数要求值类型具有operator==()的实现。     
bool contains(const T &value) const
  • 交换/移动

//将索引位置from到索引位置to  
//["A", "B", "C", "D", "E", "F"] move(1,4)-> ["A", "C", "D", "E", "B", "F"]
void move(int from, int to)

void swap(QList<T> &other)
//交换下标i j的元素    
void swapItemsAt(int i, int j)
  • 判断函数

int count(const T &value) const
int count() const
int size() const
int length() const

bool empty() const
bool isEmpty() const
//如果列表第一项/后一项等于value,则返回true; 否则返回false。  
bool startsWith(const T &value) const    
bool endsWith(const T &value) const
//预分配空间大小    
void reserve(int alloc)
  • 和其他容器互转

QSet<T> toSet() const
std::list<T> toStdList() const
QVector<T> toVector() const

[static] QList<T> fromSet(const QSet<T> &set)
[static] QList<T> fromStdList(const std::list<T> &list)
[static] QList<T> fromVector(const QVector<T> &vector)

QStringList → 字符串列表

QStringList 继承自 QList<QString> 它提供基于索引的快速访问以及快速插入和删除。 将字符串列表作为值参数传递既快速又安全。 QList的所有功能也适用于QStringList。 例如,可以使用isEmpty()来测试列表是否为空,还可以调用append()、prepend()、insert()、replace()、removeAll()、removeAt()、removeFirst()、removeLast()和removeOne()等函数来修改QStringList。 此外,QStringList提供了一些方便的函数,使处理字符串列表更容易:

  • 判断是否包含某个字符串 → 全匹配

bool contains(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool contains(QLatin1String str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
bool contains(QStringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
  • 过滤:返回包含子字符串 str 的所有字符串的列表 → 部分匹配,只要包含即可

QStringList filter(const QString &str, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
QStringList filter(QStringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
QStringList filter(const QRegExp &rx) const
QStringList filter(const QRegularExpression &re) const
  • 查找

//从左往右查找 从哪里开始查找 | 默认从0开始查
int indexOf(const QRegExp &rx, int from = 0) const
int indexOf(QStringView str, int from = 0) const
int indexOf(QLatin1String str, int from = 0) const
int indexOf(QRegExp &rx, int from = 0) const
int indexOf(const QRegularExpression &re, int from = 0) const
    
//从右往左查找    正则表达式
int lastIndexOf(const QRegExp &rx, int from = -1) const
int lastIndexOf(QStringView str, int from = -1) const
int lastIndexOf(QLatin1String str, int from = -1) const
int lastIndexOf(QRegExp &rx, int from = -1) const
int lastIndexOf(const QRegularExpression &re, int from = -1) const   
  • 连接:将QStringList中的所有字符串连接为一个字符串,每个元素由给定的分隔符(可以是空串)分隔

//支持流插入 << 返回的是一个字符串
QString join(const QString &separator) const
QString join(QStringView separator) const
QString join(QLatin1String separator) const
QString join(QChar separator) const
  • 删除:从QStringList中删除重复的元素。 返回已删除元素的数量

int removeDuplicates()
  • 替换:返回一个字符串列表,其中每个字符串在找到before文本时都将before文本替换为after文本

QStringList &replaceInStrings(const QString &before, const QString &after, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QStringList &replaceInStrings(QStringView before, QStringView after, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QStringList &replaceInStrings(const QString &before, QStringView after, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QStringList &replaceInStrings(QStringView before, const QString &after, Qt::CaseSensitivity cs = Qt::CaseSensitive)
QStringList &replaceInStrings(const QRegExp &rx, const QString &after)
QStringList &replaceInStrings(const QRegularExpression &re, const QString &after)
  • 排序:升序

void sort(Qt::CaseSensitivity cs = Qt::CaseSensitive)

 

//测试代码
#include <QStringList>
void testStringList()
{
    //构造一个字符串列表 用于存储大量的字符串
    QStringList names = {"大白","大白","小白","大黑","小黑"};
    //重载了流的方式
    names<<",.?!"<<"nullptr"<<"young"<<"loading";
    qDebug()<<names;
    //判断是否包含某个字符串 是否区分大小写
    if(names.contains("Nullptr",Qt::CaseSensitivity::CaseInsensitive))    //忽略大小写
    {
        qDebug()<<"找到了";
    }
    else
    {
        qDebug()<<"没找到";
    }
    //过滤--->部分匹配
    auto lists = names.filter("g");           //返回值类型:QStringList 需要接收一下
    for(auto str : lists)
    {
        std::cout<<str.toStdString()<<" ";    //一个个输出 转换为std的String
    }
    std::cout<<lists.size()<<std::endl;       //输出大小

    //查找-->返回下标的位置
    int pos = names.indexOf("小白");          
    qDebug()<<pos;

    //把所有的字符串连接成一个字符串
    qDebug()<<names.join(" ");                //或者用,分隔
    
    //从列表中删除重复的元素,返回已删除元素的数量
    int cnt = names.removeDuplicates();
    qDebug()<<cnt;
    qDebug()<<names;

    //把大白替换为maye
    names.replaceInStrings("大白","maye");
    qDebug()<<names;

    //排序--->按升序排列|区分大小写
    names.sort();
    qDebug()<<names;
    //c++的排序方式--->按降序排列|比较准则
    std::sort(names.begin(),names.end(),[](QString& s1,QString& s2){ return s1>s2; });
    qDebug()<<names;
}
/*输出*/

("大白","大白","小白","大黑","小黑",",.?!\","nullptr","young","loading")  //列表
找到了
loading young 2
2
"大白 大白 小白 大黑 小黑 ,.?! nullptr loading young"                     //一个字符串
1 
("大白","小白","大黑","小黑",",.?!","nullptr","young","loading")

("maye","小白","大黑","小黑",",.?!","nullptr","young","loading")

(",.?!", "loading", "maye", "nullptr", "young", "大黑", "小白", "小黑")
("小黑", "小白", "大黑", "young", "nullptr", "maye", "loading", ",.?!")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Qt --- 基本类 的相关文章

随机推荐

  • CSS层叠上下文、层叠等级、层叠顺序、z-index

    一个 片面 的理解 以往 由于自己使用z index的频率不大 所以对这个CSS属性存在比较片面的认识 一直认为z index就是用来描述定义一个元素在屏幕Z轴上的堆叠顺序 z index值越大在Z轴上就越靠上 也就是离屏幕观察者越近 最后
  • yarn、pnpm 的常用命令

    yarn 下载 npm i yarn g 查看版本 yarn version yarn v 初始化 package json yarn init yarn init y 下载包 yarn add axios 默认生产环境 yarn add
  • 【100%通过率 】【华为OD机试c++/java/python】MVP争夺战【 2022 Q4 A卷

    华为OD机试 题目列表 2023Q1 点这里 2023华为OD机试 刷题指南 点这里 题目描述 在星球争霸篮球赛对抗赛中 最大的宇宙战队希望每个人都能拿到MVP MVP的条件是单场最高分得分获得者 可以并列所以宇宙战队决定在比赛中尽可能让更
  • 1148.最大值

    include
  • Leetcode 刷题笔记(五) —— 链表篇之链表的基础操作和经典题目

    文章目录 系列文章目录 1 链表基本操作 707 设计链表 2 双指针迭代法 203 移除链表元素 206 反转链表 24 两两交换链表中的节点 3 双指针之快慢指针 19 删除链表的倒数第 N 个结点 160 相交链表 141 环形链表
  • Spring Boot CLI安装及快速入门示例

    Spring Boot CLI安装 Spring Boot是一个命令行工具 用于使用Spring进行快速原型搭建 它允许你运行Groovy脚本 这意味着你可以使用类Java的语法 并且没有那么多的模板代码 你没有必要为了使用Spring B
  • jpa|springboot|informix自定义SQL,条件判断

    jpa连mysql没什么说的 但是jpa连informix真的坑到家了 各种函数不支持 需求 在自定义sql的时候 需要判断参数是否为空 如果参数为空则不参与sql条件判断 就这么简单的一个需求 如果是jpa连mysql 那就用几个if判断
  • This application has no explicit mapping for /error, so you are seeing this as a fallback.

    Whitelabel Error Page This application has no explicit mapping for error so you are seeing this as a fallback Mon Nov 23
  • 矩阵打印(python实现)

    之前面试嵌入式软件的一道题 用c实现矩阵打印 考场上并没有写出来 之后总感觉自己写不出来也就没有去实现 在网上找也没能找到答案 结果这问题一直悬在脑海里 这才静下来想了想 发现并不难 便打算用python来实现 同时也是学习python之路
  • 基于PyTorch机器学习与深度学习实践应用与案例分析

    近年来 随着AlphaGo 无人驾驶汽车 医学影像智慧辅助诊疗 ImageNet竞赛等热点事件的发生 人工智能迎来了新一轮的发展浪潮 尤其是深度学习技术 在许多行业都取得了颠覆性的成果 另外 近年来 Pytorch深度学习框架受到越来越多科
  • azure 测试服务器性能,测试 Azure VM 网络吞吐量

    您现在访问的是微软AZURE全球版技术文档网站 若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站 请访问 https docs azure cn 带宽 吞吐量测试 NTTTCP 10 06 2020 本文内容 在
  • Python实现动态绘制爱心

    效果 源码 https download csdn net download x q x 87246985
  • 各种系统架构图及其简介

    各种系统架构图及其简介 转载请保留出处 不胜人生一场醉汇总 以下文字和架构图均在本人相关系统设计和架构方案中有所应用 原文出处 http space itpub net 6517 viewspace 609654 1 Spring架构图 S
  • QTextCodec中的setCodecForTr等终于消失了 (Qt5)

    在Qt4中 国内很多新手都喜欢 不分青红皂白地使用如下3行代码 QTextCodec setCodecForTr QTextCodec setCodecForCStrings QTextCodec setCodecForLocale 尽管之
  • linux修改host文件

    host文件位置 etc hosts vi etc hosts即可编辑 修改方式类似windows
  • 80X86微处理器堆栈指令

    压栈 弹栈指令 压栈 PUSH OP1 出栈 POP OP1 OP1可以是16位或32位的寄存器或存储器 压栈 弹栈数据存储过程 如SP 1000H BP 0FFFFH 执行下列指令后 DX SP STC Set CF 1 PUSH BP
  • 【Unity游戏开发】静态、动态合批与GPU Instancing

    https zhuanlan zhihu com p 356211912 前言 动态合批与静态合批其本质是对将多次绘制请求 在允许的条件下进行合并处理 减少cpu对gpu绘制请求的次数 达到提高性能的目的 目录 啥是合批 为啥要合批 调用D
  • socket通讯相互发送读取xml实例

    首先了解下socket通讯传输数据的特点 数据在网络传输时使用的都是字节流或字符流 Socket也不例外 所以我们发送数据的时候需要转换为字节发送 读取的时候也是以字节为单位读取 那么问题就在于socket通讯时 接收方并不知道此次数据有多
  • Python之Pandas绘图

    Pandas绘图
  • Qt --- 基本类

    位置和尺寸 在QT中我们常见的 点 线 尺寸 矩形 都被进行了封装 下面依次为大家介绍相关的类 QPoint QPoint类封装了我们常用用到的坐标点 x y 常用的 API如下 void QPoint setX int x void QP