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綁定回車鍵和確定按鈕

輸完密碼在密碼框按回車等同按了確定按鈕的效果:

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 通過 objectName 查找該控件

在代碼中,動態創建的一些控件,先通過 setObjectName(“XXX”),然后再通過 findChild 方法查找該控件:

QLabel *macLabel = new QLabel(this);
macLabel->setObjectName("mac");
 
//查找這個控件的時候
QLabel *macLabel = yourWidget->findChild<QLabel*>("mac");
qDebug() << macLabel->text();

參考:

QT里實現Windows電腦三種關機方法

讓QT 程序休眠一段時間的方法

QT延時/等待怎么寫?阻塞延時/不阻塞延時/耗時代碼的處理

QT實現快捷鍵的三種方式

QT 新建、打開 、保存文件

Qt5.QtCreator_屏蔽警告

Qt中通過代碼設置控件的objectName,和通過objectName查找該控件



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM