Skip to content

服务器托管,北京服务器托管,服务器租用-价格及机房咨询

Menu
  • 首页
  • 关于我们
  • 新闻资讯
  • 数据中心
  • 服务器托管
  • 服务器租用
  • 机房租用
  • 支持中心
  • 解决方案
  • 联系我们
Menu

Qt应用开发常用功能

Posted on 2023年5月6日 by hackdl

Qt判断当前操作系统?

#ifdef Q_OS_MAC //mac
...
#endif
 
#ifdef Q_OS_LINUX //linux
...
#endif
 
#ifdef Q_OS_WIN32 //win
...
#endif

#ifdef __arm__ //arm
...
#endif

Qt实现应用程序关闭和重启?

//关机按钮-点击槽函数
void SystemD::on_shutdownButton_clicked()
{
    //关闭应用程序
    QCoreApplication::exit();
}

//重启按钮-点击槽函数
void SystemD::on_rebootButton_clicked()
{
    //重启应用程序
    qApp->quit();
    QProcess::startDetached(qApp->applicationFilePath(), QStringList());
}

Qt实现Linux下的系统关机和重启?

先使Linux的普通用户可以在不输入密码的情况下,执行sudo reboot命令实现重启。

//关机按钮-点击槽函数
void SystemD::on_shutdownButton_clicked()
{
	QProcess::execute("sudo halt"); //UBuntu下执行关机命令(需要root权限)
}

//重启按钮-点击槽函数
void SystemD::on_rebootButton_clicked()
{
    QProcess::execute("sudo reboot"); //UBuntu下执行重启命令(需要root权限)
}

Qt 实现Windows系统关机

第一种关机方法

#include 
#include 

void ShutDown()
{
	QString program = "C:/WINDOWS/system32/shutdown.exe";
    QStringList arguments;
    arguments start(program, arguments);
}

第二种关机方法

#include 

void ShutDown()
{
	system("shutdown -s -t 00");
}

重启指令:shutdown -r -t xx
注销指令:shutdown -l -t xx

让Qt 程序休眠一段时间的方法

在Qt程序中,我们有时候会遇到这样的需求,比如让程序暂停(休息、休眠)一段时间。这里介绍以下几种方法:

一、阻塞型延时

阻塞的原理就是:在延时期间,本线程的事件循环得不到执行。
1、QThread类的sleep()
最简单的延时方法就是使用QThread类的sleep(n)、msleep(n)、usleep(n),这几个函数的不良后果就是,GUI会在延时的时间段内失去响应,界面卡死,所以,这三个函数一般只用在非GUI线程中。

QThread::sleep(5000);

2、使用定时器:死等

QTime timer = QTime::currentTime().addMSecs(5000);
while( QTime::currentTime() 

这样做会存在一个问题,当在死循环的时候,我们的界面是无法刷新,用户是不会响应用户的任何交互的。也就是让用户感觉程序已经是假死状态了。

二、非阻塞延时

原理无非就是利用事件循环,有两种原理:
1、处理本线程的事件循环
在等待中,不断强制进入当前线程的事件循环,这样可以把堵塞的事件都处理掉,从而避免程序卡死。

QTime timer = QTime::currentTime().addMSecs(5000);
while( QTime::currentTime() 

QCoreApplication::processEvents(QEventLoop::AllEvents, 100);这条语句能够使程序在while等待期间,去处理一下本线程的事件循环,处理事件循环最多100ms必须返回本语句,如果提前处理完毕,则立即返回这条语句。这也就导致了该Delay_MSec函数的定时误差可能高达100ms。
2、使用子事件循环

创建子事件循环,在子事件循环中,父事件循环仍然是可以执行的。

QEventLoop eventloop;
QTimer::singleShot(5000, &eventloop, SLOT(quit())); //创建单次定时器,槽函数为事件循环的退出函数
eventloop.exec(); //事件循环开始执行,程序会卡在这里,直到定时时间到,本循环被退出

Qt实现右键菜单

// 初始化动作
QAction *newAction = new QAction("新建",this);
// 初始化右键菜单
QMenu *rightClickMenu = new QMenu(this);
// 动作添加到右键菜单
rightClickMenu->addAction(newAction);
rightClickMenu->addSeparator();
rightClickMenu->addAction(ui->exitAction);
// 给动作设置信号槽
connect(ui->exitAction, &QAction::triggered, this, &MainWindow::on_exitAction_triggered);

// 给控件设置上下文菜单策略:鼠标右键点击控件时会发送一个void QWidget::customContextMenuRequested(const QPoint &pos)信号
this->setContextMenuPolicy(Qt::CustomContextMenu);

Qt绑定回车键和确定按钮

输完密码在密码框按回车等同按了确定按钮的效果:

connect(m_pEditPasswd, SIGNAL(returnPressed()), this, SLOT(EnterSlot()));

注意:回车键同是包含键盘区的回车键和小键盘区的回车键。

Qt打开文件与保存文件

// 打开文件
QString fileName;
fileName = QFileDialog::getOpenFileName(this,"Open File","","Text File(*.txt)");
if(fileName == "")
{
	return;
}
else
{
	QFile file(fileName);
	if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		QMessageBox::warning(this,"error","open file error!");
		return;
	}
	else
	{
		if(!file.isReadable())
			QMessageBox::warning(this,"error","this file is not readable!");
		else
		{
			QTextStream textStream(&file);
			while(!textStream.atEnd())
			{
				ui->textEdit->setPlainText(textStream.readAll());
			}
			ui->textEdit->show();
			file.close();
			flag_isOpen = 1;
			Last_FileName = fileName;
		}
	}
}

// 保存文件
QFileDialog fileDialog;
QString fileName = fileDialog.getSaveFileName(this, "save file", "", "Text File(*.txt)");
if(fileName == "")
{
    return;
}
QFile file(fileName);
if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
	QMessageBox::warning(this,"error","Open File Faile");
    return;
}
else
{
	QTextStream textString(&file);
	QString str = ui->textEdit->toPlainText();
	textString 

Qt实现截屏并保存

// 检查截图目录是否存在,若不存在则新建
QString strDir = QCoreApplication::applicationDirPath() + "/screenshot";
QDir dir;
if (!dir.exists(strDir))
{
	if(!dir.mkpath(strDir))
		QMessageBox::information(this, "Error", "新建截图目录失败!", QMessageBox::Ok);
}

// 截图并保存
QPixmap pix = this->grab(QRect(0,0,this->width(),this->height()));
QString fileName= QDateTime::currentDateTime().toString("yyyy-MM-dd-HH-mm-ss")  + ".png";//通过时间命名文件
if(!pix.save(QCoreApplication::applicationDirPath() + "/screenshot/" + fileName, "png"))
{
	QMessageBox::information(this, "Error", "保存错误 !", QMessageBox::Ok);
}
else
{
	QMessageBox::information(this, "Grab", "截图已保存在:安装目录\Screenshot目录下!", QMessageBox::Ok);
}

QtCreator 屏蔽指定警告

有两种方法可以屏蔽指定警告。
方法一:
Tools > Options > C++ > Code Model > Clang Code Model > Manage;
创建自己的配置,这里可以复制一份原来的配置 “Clang-only checks for almost everything (Copy)” ;
在Clang中添加要屏蔽的警告, 例如: -Wno-old-style-cast、-Wno-deprecated-declarations;
确定后选择刚刚创建的自己的配置。
方法二:

使用如下语句:

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"

//这里写出现警告的代码就能实现去除警告(代码写在这中间)
 
#pragma clang diagnostic pop

Qt 通过 objectName 查找该控件

在代码中,动态创建的一些控件,先通过 setObjectName(“XXX”),然后再通过 findChild 方法查找该控件:

QLabel *macLabel = new QLabel(this);
macLabel->setObjectName("mac");
 
//查找这个控件的时候
QLabel *macLabel = yourWidget->findChild("mac");
qDebug() text();

Qt模拟鼠标点击事件

通过坐标模拟鼠标事件点击事件。
关键函数:QWidget::childAt(pos);
其中 pos 是相对于 QWidget 的坐标,坐标一般有两种:全局坐标和相对坐标。通过 mapToGlobal() 之类的 API 可以转换。

QWidget* child = this->childAt(pos);
QMouseEvent *pressEvent, *releaseEvent;
pressEvent = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0, 0), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
releaseEvent = new QMouseEvent(QEvent::MouseButtonRelease, QPoint(0, 0), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
QApplication::sendEvent(child, pressEvent);
QApplication::sendEvent(child, releaseEvent);

通过以上代码,在 this 指向窗口的 pos 位置的控件(一般是 QPushButton)会接收到 clicked() 事件。

// 模拟鼠标点击的第二种方法
QTest::mouseClick(child, Qt::LeftButton, Qt::NoModifier, QPoint(0, 0));

// 发送事件的第二种方法
QCoreApplication::postEvent(child, pressEvent);
QCoreApplication::postEvent(child, releaseEvent);

// 获取当前的焦点widget
QWidget* focus = QWidget::focusWidget();

服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.e1idc.net

Related posts:

  1. 北京idc牌照申请
  2. 企业托管服务器:安全稳定的数据管理方案
  3. OpenPie 和 ChatGPT 聊聊云上数据计算的那些事儿
  4. 高效稳定的服务器托管100m服务
  5. 沭河路云服务器托管:高效稳定的云计算服务

服务器托管,北京服务器托管,服务器租用,机房机柜带宽租用

服务器托管

咨询:董先生

电话13051898268 QQ/微信93663045!

上一篇: 数据结构算法
下一篇: [错误] vue 导入excel Uncaught TypeError: Cannot read properties of undefined (reading ‘read‘)

最新更新

  • R语言用多元ARMA,GARCH ,EWMA, ETS,随机波动率SV模型对金融时间序列数据建模|附代码数据
  • mosn基于延迟负载均衡算法 — 走得更快,期待走得更稳 | 京东云技术团队
  • C++之虚函数原理 虚函数表
  • etcd:增加30%的写入性能
  • 为什么要安装虚拟机–Linux系统,我的虚拟机安装过程记录—14版本虚拟机

随机推荐

  • 所有托管在电信idc机房
  • 高效稳定,服务器托管光纤接入租用服务
  • 托管服务器遭攻击:风险与防范
  • 上海移动服务器托管:稳定高效的数据管理解决方案
  • 非插件实现wordpress网站自动内链、外链

客服咨询

  • 董先生
  • 微信/QQ:93663045
  • 电话:13051898268
  • 邮箱:dongli@hhisp.com
  • 地址:北京市石景山区重聚园甲18号2层

友情链接

  • 服务器托管
  • 服务器租用
  • 机房租用托管
  • 服务器租用托管
©2023 服务器托管,北京服务器托管,服务器租用-价格及机房咨询 京ICP备13047091号-8