zoukankan      html  css  js  c++  java
  • 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命令实现重启,具体步骤可以参考我的另一篇博客 - Linux常见问题及解决方案 的第13小结。

    //关机按钮-点击槽函数
    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实现快捷键

    ui->pushButton_Send->setShortcut(Qt::Key_Return); // 对应键盘上面大的回车键
    

    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 屏蔽指定警告

    有两种方法可以屏蔽指定警告。

    方法一:

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

    例子:

    img

    • 对应警告名称为: unused-variable
    • 格式为-Wno-警告名称
    • -Wno-unused-variable

    方法二:

    使用如下语句:

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

    参考:

    QT里实现Windows电脑三种关机方法

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

    QT延时/等待怎么写?阻塞延时/不阻塞延时/耗时代码的处理

    QT实现快捷键的三种方式

    QT 新建、打开 、保存文件

    Qt5.QtCreator_屏蔽警告


  • 相关阅读:
    技术收集
    Entity Framework的扩展库
    暂时收集
    php 处理高并发的思路
    nginx缓存优先级(缓存问题者必看)
    mysql5.5主从配置
    php源码编译常见错误解决方案
    今天开始要改变模式了
    nrpe 在ubuntu上安装遇到的问题
    zendstudio 10下载汉化
  • 原文地址:https://www.cnblogs.com/linuxAndMcu/p/11149867.html
Copyright © 2011-2022 走看看