Qt 常用函数

  1. 设置编码
#if (QT_VERSION <= QT_VERSION_CHECK(5,0,0))
#if _MSC_VER
    QTextCodec *codec = QTextCodec::codecForName("gbk");
#else
    QTextCodec *codec = QTextCodec::codecForName("utf-8");
#endif
    QTextCodec::setCodecForLocale(codec);
    QTextCodec::setCodecForCStrings(codec);
    QTextCodec::setCodecForTr(codec);
#else
    QTextCodec *codec = QTextCodec::codecForName("utf-8");
    QTextCodec::setCodecForLocale(codec);
#endif
  1. IP地址匹配,正则表达式
QRegExp rxp("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b");
if(!rxp.exactMatch(ip))
{
	   QMessageBox::warning(nullptr, QString::fromLocal8Bit("错误"),QString::fromLocal8Bit("ip地址错误!"));
   return;
}
  1. 计算用时
QDateTime dtStart = QDateTime::currentDateTime();
QDateTime dtEnd = QDateTime::currentDateTime();
double msec = dtStart.msecsTo(dtEnd);
  1. 数据类型转换
QPushButton *btn = reinterpret_cast<QPushButton *>(sender());

dynamic_cast:   通常在基类和派生类之间转换时使用,run-time   cast
const_cast:   主要针对constvolatile的转换. 
static_cast:   一般的转换,no   run-time   check.通常,如果你不知道该用哪个,就用这个。   
reinterpret_cast:   用于进行没有任何关联之间的转换,比如一个字符指针转换为一个整形数。
  • 查找控件
//查找指定类名objectName的控件
QList<QWidget *> widgets = fatherWidget.findChildren<QWidget *>("widgetname");
//查找所有QPushButton
QList<QPushButton *> allPButtons = fatherWidget.findChildren<QPushButton *>();
//查找一级子控件,不然会一直遍历所有子控件
QList<QPushButton *> childButtons = fatherWidget.findChildren<QPushButton *>(QString(), Qt::FindDirectChildrenOnly);
  • 添加 FontAwesome 字体
    //判断图形字体是否存在,不存在则加入
    QFontDatabase fontDb;
    if (!fontDb.families().contains("FontAwesome")) {
        int fontId = fontDb.addApplicationFont(":/image/fontawesome-webfont.ttf");
        QStringList fontName = fontDb.applicationFontFamilies(fontId);
        if (fontName.count() == 0) {
            qDebug() << "load fontawesome-webfont.ttf error";
        }
    }

    if (fontDb.families().contains("FontAwesome")) {
        iconFont = QFont("FontAwesome");
#if (QT_VERSION >= QT_VERSION_CHECK(4,8,0))
        iconFont.setHintingPreference(QFont::PreferNoHinting);
#endif
    }
btnPrevMonth->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); //设置策略

QtConcurrent::run(this,&DataIoPanel::sysDataInput,fileName);//启动线程

你可能感兴趣的:(Qt,qt,开发语言)