【Qt】常用基础代码汇总

文章目录
  1. 1. 1、show() 与 exec()
  2. 2. 2、设置无边框窗口
  3. 3. 3、设置窗体透明
  4. 4. 4、Qt字符串转换
  5. 5. 5、Qss读取
  6. 6. 6、QWidget自动列宽
  7. 7. 7、Qss写法参考
  8. 8. 8、Qt正则表达式
  9. 9. 9、字体相关
  10. 10. 10. Qt锁
  11. 11. 11、 计时器 定时器
    1. 11.1. 计时器
    2. 11.2. 单次定时器
  12. 12. 12、乱码问题
  13. 13. 13、 QTextBrower 设置字体颜色
  14. 14. 14 Qt http下载网络中断问题
  15. 15. 15 管理员运行程序
  16. 16. 16 QLabel 点击事件
  17. 17. 17 程序防重入
  18. 18. 18 弹窗显示在屏幕中间

概述: Qt 开发常用代码整理

[toc]

1、show() 与 exec()

show显示的是非模态对话框;exec显示的是模态对话框。

2、设置无边框窗口

1
this->setWindowFlags(Qt::FramelessWindowHint);      //设置为无边框窗口

3、设置窗体透明

1
this->setAttribute(Qt::WA_TranslucentBackground);   //设置窗体透明

4、Qt字符串转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ifdef UNICODE

#define QStringToTCHAR(x) (wchar_t*) x.utf16()
#define PQStringToTCHAR(x) (wchar_t*) x->utf16()
#define TCHARToQString(x) QString::fromUtf16((x))
#define TCHARToQStringN(x,y) QString::fromUtf16((x),(y))

#else

#define QStringToTCHAR(x) x.local8Bit().constData()
#define PQStringToTCHAR(x) x->local8Bit().constData()
#define TCHARToQString(x) QString::fromLocal8Bit((x))
#define TCHARToQStringN(x,y) QString::fromLocal8Bit((x),(y))

#endif

5、Qss读取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void Widget::InitStyle(int i)
{
m_LCD_Hour->setStyleSheet(" font: 18px black;");
if(i != 0)
{
QFile file(QString(":/Assert/qss/style%1.qss").arg(i));
file.open(QFile::ReadOnly);
this->setStyleSheet(file.readAll());
file.close();
return;
}

// m_LCD_Min->setStyleSheet("color: black; ");
// m_LCD_Sec->setStyleSheet("color: black; ");

QFile file(QString(":/Assert/qss/main.qss"));
file.open(QFile::ReadOnly);
this->setStyleSheet(file.readAll());
file.close();

}

6、QWidget自动列宽

1
2
// TreeWidget 自动列宽 add by mingming.shi 2021-10-23
ui.treeWidget->header()->setSectionResizeMode(QHeaderView::ResizeToContents);

7、Qss写法参考

QSS单独设置某控件样式

8、Qt正则表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
QRegExp rx("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b");  //IP的正则表达式
if(!rx.exactMatch(m_lineEdit->text()))
{
QMessageBox::critical(this, tr("Error"),
tr("IP WRONG.\n"
"Please Make Sure Input Correct IP!"),
QMessageBox::Ok);
return ;
}

if(m_lineEdit->text().toInt() <= 0)
{
QMessageBox::information(this, tr("Info"),
tr("IP Correct.\n"
"Input Correct IP is Saved!"),
QMessageBox::Ok);
return;
}

9、字体相关

  • 查询系统支持的字体
1
2
3
4
QFontDatabase database;
foreach (const QString &family, database.families()) {
qDebug()<<family;
}
  • 设置全局字体
    font内容为family查询到的字体名称
1
2
QFont font("family");
QApplication::setFont(font);
  • 外部加载字体
    • 字体支持ttc或ttf格式加载;
    • 使用addApplicationFont可以为系统路径,也可以资源文件。
1
2
3
4
5
6
7
8
9
int fontId = QFontDatabase::addApplicationFont("font.ttc");
QStringList fontIDs = QFontDatabase::applicationFontFamilies(fontId);
if (! fontIDs.isEmpty()) {
QFont font(fontIDs.first());
QApplication::setFont(font);
}
else {
qDebug()<<"Failed to load font.";
}

10. Qt锁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
QMutex mutex;
int number = 6;

void method1()
{
mutex.lock();
number *= 5;
number /= 4;
mutex.unlock();
}

void method2()
{
mutex.lock();
number *= 3;
number /= 2;
mutex.unlock();
}

11、 计时器 定时器

计时器

1
2
3
4
5
6
7
8
9
QTimer *timer = new QTimer;
connect(timer, SIGNAL(timeout()), this, SLOT(slotTimeOut()));
// 或者
connect(timer, &QTimer::timeout, this, [=]()mutable{
slotTimeOut();
});


timer->start(1000);

单次定时器

1
2
3
4
// 3秒后 启用下载按钮
QTimer::singleShot(3 * 1000, this, [=]() {
ui->pushBtnUpgrade->setDisabled(false);
});

12、乱码问题

在头文件添加以下代码即可。

1
2
3
#if defined(_MSC_VER) && (_MSC_VER >= 1600)
#pragma execution_character_set("utf-8")
#endif

13、 QTextBrower 设置字体颜色

1
2
3
4
5
#define TEXT_COLOR_RED(STRING)         "<font color=red>" + STRING + "</font>" "<font color=black> </font>"
#define TEXT_COLOR_BLUE(STRING) "<font color=blue>" + STRING + "</font>" "<font color=black> </font>"
#define TEXT_COLOR_GREEN(STRING) "<font color=green>" + STRING + "</font>" "<font color=black> </font>"

ui->textBrowser->setText(TEXT_COLOR_BLUE(content));

14 Qt http下载网络中断问题

使用 QNetworkAccessManager 下载文件时,网络中断返回的异常吗仍然是200,需要判断 slotFinished 函数中需要判断 error 的状态来判断下载是否正常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
void QHttpDownloadObject::Init()
{
QNetworkAccessManager *m_pManager = new QNetworkAccessManager(this);
m_pOnlinemanager = new QNetworkConfigurationManager(this);

// ("ftp", "file", "qrc", "http", "https", "data")
qDebug() << m_pManager->supportedSchemes();
m_pManager->setNetworkAccessible(QNetworkAccessManager::Accessible);

QNetworkConfigurationManager manager;
m_pManager->setConfiguration(manager.defaultConfiguration());

connect(m_pManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(slotRequestFinished(QNetworkReply*)));
}

void QHttpDownloadObject::PerformRequest(QString strUrl)
{
QNetworkRequest request;

request.setUrl(QUrl(strUrl));

request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");


m_fileTmp.setFileName(m_DestFilePath);
m_fileTmp.open(QIODevice::Append);

m_pReply = m_pManager->get(request); // get 方式

connect(m_pReply, &QNetworkReply::readyRead, this, &QHttpDownloadObject::onReadyRead);
connect(m_pReply, &QNetworkReply::downloadProgress, this, &QHttpDownloadObject::downloadProgress);
// 使用当前接口判断下载时否异常
connect(m_pReply, static_cast<void(QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), this, &QHttpDownloadObject::onError);

}

void QHttpDownloadObject::slotRequestFinished(QNetworkReply *reply)
{
disconnect(m_pReply, SIGNAL(downloadProgress(qint64, qint64)), this, SIGNAL(downloadProgress(qint64, qint64)));

if (m_fileTmp.isOpen())
{
m_fileTmp.close();
}

// 获取响应的信息,状态码为200表示正常
QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
QString strError = reply->errorString();
QNetworkReply::NetworkError error = reply->error();

qDebug() << "+++++++++" << statusCode << strError << error; // QVariant(int, 200) "Connection closed" QNetworkReply::NetworkError(RemoteHostClosedError)

if (statusCode.toInt() >= 400 || error != QNetworkReply::NoError)
{
QLOG_INFO() << "无法下载文件,错误状态码:" << statusCode << "错误信息:" << strError << error;
emit sigDownloadFinished(DOWNLOAD_CODE_NETBAD, QString(ERRORTITLE_APPACCESS_NETFAULT).arg(strError));
}
else
{
emit sigDownloadFinished(statusCode.toInt(), strError);
}

reply->close();
reply->deleteLater();
m_pManager->deleteLater();
m_pOnlinemanager->deleteLater();
}

15 管理员运行程序

  1. 管理员运行程序,限定在MSVC编译器,在项目pro文件中增加如下代码。
1
2
QMAKE_LFLAGS += /MANIFESTUAC:"level='requireAdministrator' uiAccess='false'" #以管理员运行
QMAKE_LFLAGS += /SUBSYSTEM:WINDOWS,"5.01" #VS2013 在XP运行

16 QLabel 点击事件

重写 QLabel 事件

1
2
3
4
5
6
void QCycleProgress::mousePressEvent(QMouseEvent* event)
{
emit clicked();

QLabel::mousePressEvent(event);
}

17 程序防重入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "qrcode.h"
#include <QSharedMemory>
#include <QApplication>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//创建运行时只允许存在一个程序
static QSharedMemory *shareMem = new QSharedMemory("SingleAPP");
//判断如果存在存直接退出
if(!shareMem->create(1)){
qApp->quit();
return -1;
}else{
int result = -1;
while (result !=0) {
Create_qrcode w;
w.setWindowIcon(QIcon(":/images/main_logo.ico"));
w.show();
result= a.exec(); //!退出时如果为零,正常退出,否则重启程序
}
return result;
}
}

18 弹窗显示在屏幕中间

使用

1
2
3
4
5
6
7
8
void QTrayTooltipForm::show()
{
placeTip(QCursor::pos());

UpdateStatus();

return QWidget::show();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void QTrayTooltipForm::placeTip(const QPoint& pos)
{
QRect screen = QApplication::desktop()->screenGeometry(QApplication::desktop()->screenNumber(pos));

QPoint p = pos;
p += QPoint(2,16);
if (p.x() + this->width() > screen.x() + screen.width())
p.rx() -= 4 + this->width();
if (p.y() + this->height() > screen.y() + screen.height())
p.ry() -= 24 + this->height();
if (p.y() < screen.y())
p.setY(screen.y());
if (p.x() + this->width() > screen.x() + screen.width())
p.setX(screen.x() + screen.width() - this->width());
if (p.x() < screen.x())
p.setX(screen.x());
if (p.y() + this->height() > screen.y() + screen.height())
p.setY(screen.y() + screen.height() - this->height());
this->move(p);
}