Qt应用开发常用功能

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 <Windows.h>
#include <QProcess>

void ShutDown()
{
    
    
	QString program = "C:/WINDOWS/system32/shutdown.exe";
    QStringList arguments;
    arguments << "-s";
    QProcess *myProcess = new QProcess();
    myProcess->start(program, arguments);
}

第二种关机方法

#include <Windows.h>

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() < timer ); //等待时间流逝5秒钟

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

二、非阻塞延时

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

QTime timer = QTime::currentTime().addMSecs(5000);
while( QTime::currentTime() < timer );
	QCoreApplication::processEvents(QEventLoop::AllEvents, 100);

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 << str;
	Last_FileContent = str;
	file.close();
}

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<QLabel*>("mac");
qDebug() << macLabel->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();

猜你喜欢

转载自blog.csdn.net/houxian1103/article/details/130354099