0
点赞
收藏
分享

微信扫一扫

七、Qt之开机启动、设置全局编码、设置样式、加载翻译文件、UI线程延时和窗体居中显示

备注:要想使用 ​​qApp​​​ 宏,该类必须继承 ​​QObject​​​ 或者引入 ​​Q_OBJECT​​ 宏

一、开机启动

//设置为开机启动
static void autoRunWithSystem(bool ifAutoRun, QString appName, QString appPath) {
QSettings *reg = new QSettings(
"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",//QSettings::NativeFormat(在windows平台可读写注册表)
QSettings::NativeFormat);

if (ifAutoRun) {
reg->setValue(appName, appPath);
} else {
reg->setValue(appName, "");
}
}

二、设置全局UTF-8编码

//设置编码为UTF8
static void setTextCode(const QString sForName="UTF-8") {
#if (QT_VERSION <= QT_VERSION_CHECK(5,0,0))
QTextCodec *codec = QTextCodec::codecForName(sForName);
QTextCodec::setCodecForLocale(codec);
QTextCodec::setCodecForCStrings(codec);
QTextCodec::setCodecForTr(codec);
#endif
}

三、设置样式

//设置指定样式
static void setStyle(const QString &qssFile) {
QFile file(qssFile);
if (file.open(QFile::ReadOnly)) {
//QLatin1String类对US-ASCII/Latin-1编码的字符串进行了简单封装,可理解为关于const char*的一个浅封装。
QString qss = QLatin1String(file.readAll());
//qApp宏:指向整个应用程序
qApp->setStyleSheet(qss);
//将颜色写在了 qss 文件中
QString PaletteColor = qss.mid(20, 7);
//设置主题颜色
qApp->setPalette(QPalette(QColor(PaletteColor)));
file.close();
}
}

四、加载翻译文件

//加载中文字符
static void setChinese() {
QTranslator *translator = new QTranslator(qApp);
translator->load(":/image/qt_zh_CN.qm");
qApp->installTranslator(translator);
}

五、在UI线程休眠,但不卡UI界面

/**
* 延时:
* 传入参数mSec,使程序延时mSec毫秒。这种方法不会阻塞当前线程,尤其适合Qt的单线程带UI程序,
* 或者UI线程,因为线程阻塞时,很明显的现象就是UI卡死。当然,你也可以更改addMSecs为addSecs使
* 程序延时msec秒。
* 如果去掉QCoreApplication::processEvents(QEventLoop::AllEvents, 100); 可以延时,但
* 也会阻塞线程.
* QCoreApplication::processEvents(QEventLoop::AllEvents, 100);使程序在while等待期间,
* 去处理一下本线程的事件循环,处理事件循环最多100ms必须返回本语句,如果提前处理完毕,则立即返
* 回这条语句。
*/
static void sleep(int mSec) {
QTime dieTime = QTime::currentTime().addMSecs(mSec);

while ( QTime::currentTime() < dieTime ) {
//处理本线程的时间循环,防止阻塞 UI 线程,造成 UI 卡死的现象
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
}

六、窗体居中显示

//窗体居中显示
static void moveFormToCenter(QWidget *frm) {
int frmX = frm->width();
int frmY = frm->height();

QDesktopWidget dwt;

int deskWidth = dwt.availableGeometry().width();
int deskHeight = dwt.availableGeometry().height();

QPoint movePoint(deskWidth / 2 - frmX / 2, deskHeight / 2 - frmY / 2);
frm->move(movePoint);
}

七、判断是否是IP

//判断是否是IP地址
static bool isIP(const QString sIP) {
QRegExp RegExp("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
return RegExp.exactMatch(sIP);
}


举报

相关推荐

0 条评论