Qt经验集合

本文围绕Qt开发分享了众多实用技巧,涵盖QLineEdit的密码设置、提示语添加、输入补全等功能,还包括数据大小端设置、qDebug输出控制、非事件阻塞延时等操作,同时介绍了md5加密、控件样式设置、文件路径输出等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

你点一下试试

QLineEdit设置密码不可见

使用枚举(qt库所有):

	enum EchoMode { Normal, NoEcho, Password, PasswordEchoOnEdit };

使用代码如下:

    ui->keyNewLineEdit->setEchoMode(QLineEdit::Password);
    ui->keyOldLineEdit->setEchoMode(QLineEdit::Password);

QLineEdit添加提示语

在QLineEdit无输入的时候,框内显示淡化的提示内容,如下图所示:
在这里插入图片描述
实现代码:

    ui->lineEdit_cmd->setPlaceholderText("输入命令");
    ui->lineEdit_pwd->setPlaceholderText("输入密码");

QLineEdit输入补全

实现效果如下图:
在这里插入图片描述
实现代码:

	QStringList buff;
    buff << "11" << "111" << "1111" << "222" << "333"<<"this is a test"<<"";
    QCompleter *com = new QCompleter(buff,this);
    com->setCaseSensitivity(Qt::CaseSensitive);
    ui->lineEdit->setCompleter(com);

补全系统文件路劲代码:

	QCompleter *completer = new QCompleter(this);
	QDirModel *dirModel = new QDirModel();
	completer->setModel(dirModel);
	ui->lineEdit->setCompleter(completer);

效果:
在这里插入图片描述

QLineEdit输入限制

直接使用代码实现限制:

QDoubleValidator *pValidator = new QDoubleValidator(-180.0, 180.0 , 2, validatorLineEdit);
pValidator->setNotation(QDoubleValidator::StandardNotation);
ui->lineEdit->setValidator(pValidator);

也可以使用正则表达式限制,可参考下面链接:
https://blog.csdn.net/weixin_42887343/article/details/106262608

设置数据大小端

使用枚举(qt库所有):

    enum ByteOrder {
        BigEndian = QSysInfo::BigEndian,
        LittleEndian = QSysInfo::LittleEndian
    };

在上下位机通讯中经常使用到该操作,代码如下:

    QByteArray arrayItemInfo;
    QDataStream out(&arrayItemInfo, QIODevice::ReadWrite);
    out.setByteOrder(QDataStream::LittleEndian);  //设置小端格式

qDebug输出函数、文件等相关信息

可使用标准C++中的宏定义__FUNCTION__、FILE__和__LINE,程序预编译时,预编译器将用所在的函数名,文件名和行号替换。qt中可使用Q_FUNC_INFO宏输出“类名::函数名”
代码如下:

    qDebug() << __FUNCTION__ << __LINE__;
	qDebug()<<"In language switching... for:"<<Q_FUNC_INFO;

非事件阻塞延时

使用这种延时方式可实时响应qt事件,而不会造成事件阻塞。

void Delay(int msec)
{
    QTime dieTime = QTime::currentTime().addMSecs(msec);
    while( QTime::currentTime() < dieTime )
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}

加快qtCreator编译速度

添加Make 参数 -j 4 ,使用多线程编译,如下图所示:
在这里插入图片描述

隐藏QTabwidget的tab

ui->tabWidget->findChildren<QTabBar*>().at(0)->hide();

如果qt版本是5.0以上,还可以使用如下操作:

ui->tabWidget->tabBar()->hide();

md5加密计算

QString passwordBuff = "123456";
passwordBuff = QCryptographicHash::hash(passwordBuff.toAscii(),QCryptographicHash::Md5 ).toHex();
return passwordBuff.compare("123456");

按钮选中时去掉虚线边框

按钮样式中添加qss语句:

 outline: none;

或者直接在ui设计界面的属性里面,将聚焦属性设为无聚焦,这样也可以更好达到目的,如果是使用ui添加的控件,建议使用该方法。
在这里插入图片描述

label内容自动换行

勾选wordwrap属性可实现自动换行,如下图:
在这里插入图片描述

设置qlabel控件内容可被选择复制

    ui->label_checkCode->setTextInteractionFlags(Qt::TextSelectableByMouse);

tr()函数正确使用方法

非常不建议tr中包含中文,尽管现在的新版Qt支持中文到其他语言的翻译,但是很不规范,tr的本意是包含英文,然后翻译到其他语言比如中文。如果没有翻译的需求,最好禁用tr,tr需要开销的,Qt默认会认为他需要翻译,会额外进行特殊处理。

split、join字符串分割与重组

QString str;
QStringList strList;
strList = str.split(",");
str = strList.join(",");

设置QLineEdit为可清空

这个接口好像只有qt5才有,qt4不存在。

ui->mLineEdit->setClearButtonEnabled(true);

效果如下图,输入框中右边的清空控件:
在这里插入图片描述

设置主界面背景颜色

    QPalette palette(this->palette());
    palette.setColor(QPalette::Background, QColor(220,220,220));
    this->setPalette(palette);

禁止qDebug输出

在项目的pro文件中添加定义如下:

DEFINES+= QT_NO_DEBUG_OUTPUT

设置QCombox下拉框可编辑

    ui->comboBox->setEditable(true);

搜索QByteArray中的内容

比如,搜索数据中连续为0x69、0xaa的数据。

int index = _cache.indexOf("\x69\xaa");		//_cache为QByteArray类型

qt非阻塞延时操作

void MyClass::sleep(int msec)
{
    QTime dieTime = QTime::currentTime().addMSecs(msec);
    while( QTime::currentTime() < dieTime )
    	QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}

qt子控件聚焦切换

qt子控件的切换默认使用tab键,但是特使情况下可其他操作切换,如调用下面函数:

	focusNextChild();

此函数一般配合事件过滤器使用,如下,按空格键实现聚焦切换:

textEdit->installEventFilter(this);		//为textEdit安装事件过滤器

void MyLineEdit::keyPressEvent(QKeyEvent *event) 
{ 
     if (event->key() == Qt::Key_Space)
     { 
         focusNextChild(); 
     }
}

使用QUuid生成唯一标识

UUID 为通用唯一标识,是由某种算法生成的 16 字节(128 位)数字,旨在保证 UUID 在使用它的分布式计算环境中是唯一的。
警告: 此功能仅适用于 Windows 平台(qt官方原话)。
非windows平台UUID由qrand()种子生成,所以产生的UUID不保证具有唯一性。

#include <QUuid>

QString id = QUuid::createUuid().toString();
id = QUuid::createUuid().toString().remove('-').remove('{').remove('}');	//唯有数字字母的ID

Relase版本可调试

一般来说,relase编译的时候,为了尽量减少输出文件的存储,会去掉所有调试信息编译,需要可调试的话,需要在pro文件中添加如下代码:

    QMAKE_CXXFLAGS_RELEASE = $$QMAKE_CFLAGS_RELEASE_WITH_DEBUGINFO
    QMAKE_LFLAGS_RELEASE = $$QMAKE_LFLAGS_RELEASE_WITH_DEBUGINFO

同事对应编译输出的文件同样占的存储空间也大。

设置目标文件输出路劲

win32:CONFIG(debug, debug|release):DESTDIR = $$PWD/build/bin_debug
win32:CONFIG(release, debug|release):DESTDIR = $$PWD/build/bin_release

double、float的比较、判断

浮点数比较

static inline Q_DECL_UNUSED bool qFuzzyCompare(double p1, double p2);
static inline Q_DECL_UNUSED bool qFuzzyCompare(float p1, float p2);

判断浮点数为0

static inline Q_DECL_UNUSED bool qFuzzyIsNull(double d);
static inline Q_DECL_UNUSED  bool qFuzzyIsNull(float f);

QDateEdit、QTimeEdit自定义编辑框

系统统一ui风格,而同样需要修改QDateEditQTimeEdit样式保持一致,可使用如下方法:

QDateEdit dateEdit;
QTimeEdit timeEdit;
dateEdit->setLineEdit(new WBCustomLineEdit(dateEdit));
timeEdit->setLineEdit(new WBCustomLineEdit(timeEdit));

WBCustomLineEdit为你们自定义的LineEdit。

QElapsedTimer 计时器

QElapsedTimer timer;  
timer.start();  
yourOperation();  
int mSec = timer.elapsed();

qt获取当前屏幕像素大小

QScreen *screen = QGuiApplication::screenAt(QCursor().pos());
if(!screen) return;
QRect screenRect = screen->geometry();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值