天天看点

Qt零碎记录

文章目录

  • ​​一、隐藏任务栏窗口图标​​
  • ​​二、Qt关闭电脑​​
  • ​​三、Qt常用路径​​
  • ​​四、Qt读写文件​​
  • ​​五、QByteArray和QString互转​​
  • ​​六、connect各式写法​​
  • ​​七、获取字符串的像素宽高​​
  • ​​八、非阻塞延时​​
  • ​​九、获取本机IP​​
  • ​​十、QTextBrowser文字​​
  • ​​十一、QString截取字符串​​
  • ​​十二、隐藏鼠标​​
  • ​​十三、枚举值与字符串互转​​
  • ​​十四、QMainWindow添加菜单栏、工具栏、状态栏​​
  • ​​十五、禁用中文输入法​​
  • ​​十六、使用QStringList设置QSS​​
  • ​​十七、QLabel文字显示不全省略​​
  • ​​十八、拷贝文件、文件夹​​
  • ​​十九、删除文件或者文件夹​​
  • ​​二十、Qt使用HTML显示文字​​
  • ​​二十一、隐藏菜单项​​

一、隐藏任务栏窗口图标

QT里的parent参数:我们在写界面的时候,几乎每个构造函数里都会有一个parent参数。这个参数通常是​

​QObject*​

​​ 或者是​

​QWidget*​

​ 类型,初始值0;

我们基本上也没理会,但是你有没有想过,这个parent有什么作用呢?

“对话框”,对话框一般是不作为顶层容器出现的,因此在任务栏上是没有对话框的位置的,指定对话框的parent属性,任务栏就不会出现图标。如果你不指定,这个对话框就成为顶层容器了,任务栏会出现图标。利用这个特性,就可以实现我们的窗体是否需要在任务栏上出现。

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QApplication::setQuitOnLastWindowClosed(false);

    QWidget* parent = new QWidget;
    MainWindow* w = new MainWindow(parent);
    w->show();
    w->activateWindow();
    int ret = a.exec();
    delete parent;
    return ret;
}      
运行软件后,任务栏一般都会有一个软件的图标,使用此行代码可以将任务栏窗口图标隐藏起来

二、Qt关闭电脑

#include <Windows.h>

system("shutdown -s -t 00");  //关机
system("shutdown -r -t 00");  //重启
system("shutdown -l -t 00");  //注销      

​-t​

​​: 指令执行延时时间,例如​

​system("shutdown -s -t 00");​

​就是马上关机。

三、Qt常用路径

应用程序可执行文件所在目录

QString applicationDirPath = QCoreApplication::applicationDirPath();      

应用程序可执行文件的文件路径

QString applicationFilePath = QCoreApplication::applicationFilePath();      

四、Qt读写文件

QFile::open()函数打开文件是需要传递QIODevice::OpenModeFlag枚举类型的参数,决定以什么方式打开

QIODevice::OpenModeFlag枚举类型 说明
QIODevice::ReadOnly 以只读方式打开文件,用于载入文件
QIODevice::WriteOnly 以只写方式打开文件,用于保存文件
QIODevice::ReadWrite 以读写方式打开
QIODevice::Append 以添加模式打开,新写入文件的数据添加到文件尾部
QIODevice::Truncate 以截取方式打开文件,文件原有的内容全部被删除
QIODevice::Text 读取时“\n”被自动翻译为换行符,写入时字符串结束符会自动翻译为系统平台的编码,如 Windows 平台下是“\r\n”

用QFile类的IODevice读写功能进行读写

= "xxx";
  QFile file(filePath);
  if(!file.exists()) {
    return;
  }
  if(!file.open(QIODevice::ReadOnly |QIODevice::Text)) {
    return
  }
  while(!file.atEnd()) {
    QString lineStr = file.readLine();
  }
  
  file.close();      

用QFile和QTextStream结合起来,用流(Stream)的方法进行文件读写

= "xxx";
  QFile file(filePath);
  if(!file.exists()) {
    return;
  }
  if(!file.open(QIODevice::WriteOnly |QIODevice::Text)) {
    return
  }
  QTextStream Stream(&file);  //用文本流读取文件
  Stream << "内容1";
  Stream << "内容2";
  Stream << "内容3";

  file.close();      

五、QByteArray和QString互转

QByteArray转QString

QByteArray bytes("hello world");
QString data = bytes;   // QByteArray转QString方法1      

QString转QByteArray

QString data("yudabo");  
QByteArray bytes = data.toUtf8();    // QString转QByteArray方法1 
 
QString data("yudabo");  
QByteArray bytes = data.toLatin1();  // QString转QByteArray方法2      

六、connect各式写法

//Qt4
connect(sender,SIGNAL(sig_xxx(para1,para2)),receiver,SLOT(slot_xxx(para1,para2)));
//示例
connect(ui->btn,SIGNAL(sig_btn()),this,SLOT(slot_btn()));

//Qt5不带参数
connect(sender,&className::sig_xxx,receiver,&className::slot_xxx);
//示例
connect(ui->btn,&QPushButton::sig_btn),this,&QMainWindow::slot_btn));

//Qt5带参数
connect(sender,QOverload<para_type>::of(&className::sig_xxx),receiver,QOverload<para_type>::of(&className::slot_xxx));
//示例
connect(ui->btn,QOverload<bool>::of(&QPushButton::sig_btn)),this,QOverload<bool>::of(&QMainWindow::slot_btn)));

lamda表达式
connect(sender,&className::sig_xxx,[=]{
  ...
});
//示例
connect(ui->btn,&QPushButton::sig_btn,[=]{
  qDebug()<<"按钮按下!";
});      

七、获取字符串的像素宽高

//设置字体
QFont font;
font.setFamily("Microsoft YaHei");
font.setPointSize(8);
QFontMetrics fm(font);
QRect rec = fm.boundingRect("这是要获取宽度和高度的字符串");
//字符串所占的像素宽度,高度
int textWidth = rec.width();
int textHeight = rec.height();      

八、非阻塞延时

void sleep(int sectime)
{
    QTime dieTime = QTime::currentTime().addMSecs(sectime);
 
    while (QTime::currentTime() < dieTime) {
        QCoreApplication::processEvents(QEventLoop::AllEvents, maxtime);
    }
}      

九、获取本机IP

QString Widget::getIP() //获取ip地址
{
    QString ip_address;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    for (int i = 0; i < ipAddressesList.size(); ++i)
    {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&  ipAddressesList.at(i).toIPv4Address())
        {
            ip_address = ipAddressesList.at(i).toString();
        }
    }
    if (ip_address.isEmpty())
        ip_address = QHostAddress(QHostAddress::LocalHost).toString();
    return ip_address;
}      

十、QTextBrowser文字

ui->msgBrowser->setTextColor(Qt::blue);  //整体设置颜色
ui->msgBrowser->setCurrentFont(QFont("Times New Roman", 12));  //整体设置字体

QString temp = "xxx";
ui->msgBrowser->append("<font color=\"#FF0000\">" + temp + "</font>");  //追加xxx(红色)
ui->msgBrowser->append("<font color=\"#00FF00\">" + temp + "</font>");  //追加xxx(绿色)
ui->msgBrowser->append("<font color=\"#0000FF\">" + temp + "</font>");  //追加xxx(蓝色)      

十一、QString截取字符串

QString::mid

QString mid(int position, int n = -1) const;  //函数原型
//position: 开始下标
//n: 截取长度

//示例
QString str;
QString csv = "0;1;2;3;4;5";

str = csv.mid(0,1);  //0
str = csv.mid(0,2);  //0;
str = csv.mid(0,3);  //0;1
str = csv.mid(0,4);  //0;1;      

QString::section

QString section(QChar sep, int start, int end = -1, SectionFlags flags = SectionDefault) const;  //函数原型
//sep:分隔字符
//start:开始切割的位置
//end: 结束切割的位置
//flags: 切割行为定义

//示例
QString str;
QString csv = "0;1;2;3;4;5";

str = csv.section(‘;’,0,0);  //1
str = csv.section(‘;’,1,1);  //2
str = csv.section(‘;’,2,3);  //2;3      

QString::split

QStringList split(QChar sep, SplitBehavior behavior = KeepEmptyParts,Qt::CaseSensitivity cs = Qt::CaseSensitive) const;  //函数原型
//sep: 分隔字符

//示例
QStringList list;
QString csv = "0;1;2;3;4;5";

list = csv.split(';');  
//list[0] = '0';
//list[1] = '1';
//list[2] = '2';
//list[3] = '3';
//list[4] = '4';
//list[5] = '5';      

十二、隐藏鼠标

qApp->setOverrideCursor(Qt::BlankCursor);      

十三、枚举值与字符串互转

class Cenum : public QObject
{
    Q_OBJECT
public:
    Cenum(){}

    enum ElementType
    {
        one,
        two,
        three
    };
    Q_ENUM(ElementType)
};      
qDebug()<<"Cenum::one: "<<Cenum::one;                                     
qDebug()<<"======================";                                       
QMetaEnum metaEnum = QMetaEnum::fromType<Cenum::ElementType>();           
qDebug()<<"Cenum::one: "<<metaEnum.valueToKey(Cenum::one);  //enum转QString
qDebug()<<"Cenum::one: "<<metaEnum.keysToValue("one");      //QString转enum      

十四、QMainWindow添加菜单栏、工具栏、状态栏

void MainWindow::CreateMenuBar()
{
    QMenuBar * menuBar = new QMenuBar(this);

    QMenu * menuFile = new QMenu("File", this);
    QAction * newFile = new QAction(QIcon(), "NewFile", this);
    QAction * openFile = new QAction(QIcon(), "OpenFile", this);
    QAction * save = new QAction(QIcon(), "Save", this);
    menuFile->addAction(newFile);
    menuFile->addAction(openFile);
    menuFile->addAction(save);

    QMenu * menuEdit = new QMenu("Edit", this);
    QAction * cut = new QAction(QIcon(), "Cut", this);
    QAction * copy = new QAction(QIcon(), "Copy", this);
    QAction * paste = new QAction(QIcon(), "Paste", this);
    menuEdit->addAction(cut);
    menuEdit->addAction(copy);
    menuEdit->addAction(paste);

    menuBar->addMenu(menuFile);
    menuBar->addMenu(menuEdit);

    this->setMenuBar(menuBar);
}

void MainWindow::CreateToolBar()
{
    QToolBar * toolBar1 = new QToolBar(this);
    toolBar1->setObjectName("toolBar1");
    QAction * action1_1 = new QAction("action1_1", this);
    QAction * action1_2 = new QAction("action1_2", this);
    QAction * action1_3 = new QAction("action1_3", this);
    QAction * action1_4 = new QAction("action1_4", this);
    toolBar1->addAction(action1_1);
    toolBar1->addAction(action1_2);
    toolBar1->addAction(action1_3);
    toolBar1->addAction(action1_4);

    QToolBar * toolBar2 = new QToolBar(this);
    toolBar2->setObjectName("toolBar2");
    QAction * action2_1 = new QAction("action2_1", this);
    QAction * action2_2 = new QAction("action2_2", this);
    QAction * action2_3 = new QAction("action2_3", this);
    QAction * action2_4 = new QAction("action2_4", this);
    toolBar2->addAction(action2_1);
    toolBar2->addAction(action2_2);
    toolBar2->addAction(action2_3);
    toolBar2->addAction(action2_4);

    QToolBar * toolBar3 = new QToolBar(this);
    toolBar3->setObjectName("toolBar3");
    QAction * action3_1 = new QAction("action3_1", this);
    QAction * action3_2 = new QAction("action3_2", this);
    QAction * action3_3 = new QAction("action3_3", this);
    QAction * action3_4 = new QAction("action3_4", this);
    toolBar3->addAction(action3_1);
    toolBar3->addAction(action3_2);
    toolBar3->addAction(action3_3);
    toolBar3->addAction(action3_4);

    this->addToolBar(toolBar1);
    this->addToolBar(toolBar2);
    this->addToolBar(toolBar3);
}

void MainWindow::CreateStatusBar()
{
    //创建状态栏
    QStatusBar *status = new QStatusBar(this);
    status->setObjectName("status");
    status->setObjectName("状态栏");
    status->setStyleSheet("QStatusBar::item{border: 0px}"); //设置不显示label的边框

    //主窗口添加状态栏
    this->setStatusBar(status);

    //创建标签
    QLabel *statusLabel = new QLabel("我是状态栏", this);

    //状态栏添加信息
    status->showMessage("我在3秒后会消失", 3000);//显示在左侧,并且3秒后自动消失

    status->addPermanentWidget(statusLabel);//添加右侧标签(永久性)
}      

十五、禁用中文输入法

this->setAttribute(Qt::WA_InputMethodEnabled,false);      
#include <windows.h>
#pragma  comment(lib,"User32.lib")

HKL  hCurKL;
void disableIME();
void enableIME();
//----------------------------------------------------------------------
void Widget::disableIME()
{
    hCurKL = GetKeyboardLayout(0);
    LoadKeyboardLayout((LPCWSTR)QString("0x0409").utf16(), KLF_ACTIVATE);
}

void Widget::enableIME()
{
    ActivateKeyboardLayout(hCurKL, 0);
}      

十六、使用QStringList设置QSS

QStringList qss;
qss.append(QString("background-color: red;"));
qss.append(QString("border: none;"));
this->setStyleSheet(qss.join(""));      

十七、QLabel文字显示不全省略

//函数原型
QString QFontMetrics::elidedText(const QString &text, Qt::TextElideMode mode, int width, int flags = 0) const

第二个参数为文本缩略后,省略号所在的位置,可选:
Qt::ElideLeft      0     省略号应出现在文本的开头;
Qt::ElideRight      1     省略号应出现在文本的末尾;
Qt::ElideMiddle      2     省略号应出现在文本的中间;
Qt::ElideNone      3     省略号不应出现在文本中;      
//使用示例
QString str = ui->label->text();
QFontMetrics metrics(ui->label->font());
if (metrics.width(str) > ui->label->width()) {
  str = QFontMetrics(ui->label->font()).elidedText(str, Qt::ElideRight, ui->label->width());
}
ui->label->setText(str);      

十八、拷贝文件、文件夹

//拷贝文件:
bool MyTest007::copyFileToPath(QString sourceDir ,QString toDir, bool coverFileIfExist)
{
  toDir.replace("\\","/");
  if (sourceDir == toDir){
    return true;
  }
  if (!QFile::exists(sourceDir)){
    return false;
  }
  QDir *createfile     = new QDir;
  bool exist = createfile->exists(toDir);
  if (exist){
    if(coverFileIfExist){
      createfile->remove(toDir);
    }
  }//end if
 
  if(!QFile::copy(sourceDir, toDir))
  {
    return false;
  }
  return true;
}      
//拷贝文件夹:
bool MyTest007::copyDirectoryFiles(const QString &fromDir, const QString &toDir, bool coverFileIfExist)
{
  QDir sourceDir(fromDir);
  QDir targetDir(toDir);
  if(!targetDir.exists()){    /**< 如果目标目录不存在,则进行创建 */
    if(!targetDir.mkdir(targetDir.absolutePath()))
      return false;
  }
 
  QFileInfoList fileInfoList = sourceDir.entryInfoList();
  foreach(QFileInfo fileInfo, fileInfoList){
    if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")
      continue;
 
    if(fileInfo.isDir()){    /**< 当为目录时,递归的进行copy */
      if(!copyDirectoryFiles(fileInfo.filePath(), 
        targetDir.filePath(fileInfo.fileName()),
        coverFileIfExist))
        return false;
    }
    else{            /**< 当允许覆盖操作时,将旧文件进行删除操作 */
      if(coverFileIfExist && targetDir.exists(fileInfo.fileName())){
        targetDir.remove(fileInfo.fileName()); 
      }
 
      /// 进行文件copy
      if(!QFile::copy(fileInfo.filePath(), 
        targetDir.filePath(fileInfo.fileName()))){
          return false;
      }
    }
  }
  return true;
}      

十九、删除文件或者文件夹

清空文件夹内所有文件或者文件夹

void clearAllFileAndDir(const QString& path)
{
    if(path.isEmpty()) {
        return;
    }
    
    QDir dir(path);
    if(!dir.exist()) {
        return;
    }

    QDirIterator DirsIterator(path, QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot, QDirIterator::NoIteratorFlags);
    while(DirsIterator.hasNext()) {
        if (!Dir.remove(DirsIterator.next())) {    // 删除文件操作如果返回否,那它就是目录
            QDir(DirsIterator.filePath()).removeRecursively(); // 删除目录本身以及它下属所有的文件及目录
        }
    }
}      

删除文件夹或者文件

bool MainWindow::DeleteFileOrFolder(const QString& strPath) //要删除的文件夹或文件的路径
{
    if (strPath.isEmpty() || !QDir().exists(strPath)) //是否传入了空的路径||路径是否存在
        return false;

    QFileInfo FileInfo(strPath);

    if (FileInfo.isFile()) //如果是文件
        QFile::remove(strPath);
    else if (FileInfo.isDir()) //如果是文件夹
    {
        QDir qDir(strPath);
        qDir.removeRecursively();
    }
    return true;
}      

二十、Qt使用HTML显示文字

1、QLabel的文本显示是支持html标签的,使用html有时候能很便捷的实现一些效果,例如:显示超链接

ui->label->setText(tr("Learn more please visit: <a style=color:#32bc84; href = http://www.baidu.com>www.baidu.com</a>"));      
connect(ui->label, &QLabel::linkActivated, this, [=](const QString& link){
  QDesktopServices::openUrl(QUrl(link));
});      
void Form::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    QTextDocument doc;
    doc.setHtml(html);
    //设置文本宽度
    doc.setTextWidth(200);
    //指定绘制区域
    doc.drawContents(&painter, QRect(0, 0, 200, 70));
}      

二十一、隐藏菜单项

ui->menu->menuAction()->setVisible(false);