Qt应用和错误笔记

1. qt this does not seem to be a debug build

Com.pro中CONFIG += qt warn_off release改为CONFIG += qt warn_off debug,Buid->Rebuild All即可。

Qt Creator->工具->选项->构建套件->手动设置->调试器->编辑->

引擎->GDB引擎

二进制:P:\Qt\qtcreator-2.8.0\mingw\bin\gdb.exe

2.QtCreator无法打开帮助

工具->选项->帮助->文档

在弹出的“添加文档”对话框中找到Qt SDK安装目录下的“Documentation”文件夹,根据自己的需要选择安装对应的“*.qch”文件即可。

http://blog.163.com/ljf_gzhu/blog/static/13155344020128244199294/

3.QtCreator无法输入中文

sudo apt-get install fcitx-frontend-qt5

重启系统。注:用的是fcitx搜狗拼音。

4.QSplashScreen不能正常显示图片

应用程序启动速度太快导致。

5.模态与非模态

QDialog *pDlg=new QDialog(this); pDlg->setModal(true); pDlg->show();

QWidget *pWid = new QWidget(this);

pWid->setWindowModality(Qt::ApplicationModal);

//pWid->setAttribute(Qt::WA_ShowModal, true);

pWid->show(); *pWid = new QWidget(this);

pWid->setWindowModality(Qt::ApplicationModal);

//pWid->setAttribute(Qt::WA_ShowModal, true);

pWid->show();

http://blog.csdn.net/wadfji/article/details/54097418

6. 隐藏标题栏

QApplication a(argc, argv);

Widget w;

w.setWindowFlags(Qt::X11BypassWindowManagerHint);  //去掉标题栏

w.show();

7.设置图标

7.1 方式1

QApplication a(argc,argv);

a.setWindowIcon(QIcon(":/main.ico"));

7.2 方式2

第一步:创建(下载)一个包含图标图像的ICO文件,并将其保存在源文件目录下,可命名为myapp.ico;

第二步:创建一个.rc文件,包含如下内容:

IDI_ICON1 ICON    DISCARDABLE     "myappico.ico" 

第三步:工程文件myapp.pro文件中写入如下内容:

RC_FILE += myapp.rc 

http://blog.csdn.net/chenlong12580/article/details/7389588

8.设置背景图片

8.1 方式1

使用stylesheet设置背景图片还是有一些要注意的,如果是在mainwindow和dialog中,直接右键change style sheet在add resource中选择background-image或者

 

border-image,选择资源文件中的图片就行了(前者是按像素显示图片,后者可根据窗体大小来自动缩放图片,通常使用后者,前者如果界面与图片大小不一样,

 

则背景的显示可能就不是整张图片了

8.2 方式2

首先设置autoFillBackground属性为真

然后定义一个QPalette对象

设置QPalette对象的背景属性(颜色或图片)

最后设置QWidget对象的Palette

实例:

QWidget *widget = new QWidget;

widget->setAutoFillBackground(true);

QPalette palette;

palette.setColor(QPalette::Background, QColor(192,253,123));

//palette.setBrush(QPalette::Background, QBrush(QPixmap(":/background.png")));

widget>setPalette(palette);

9.在QListView中显示图标

头文件部分代码:

QListView *listview; 

QStandardItem *s1,*s2,*s3,*s4,*s5,*s6; 

QStandardItemModel* slm; 

     

源文件部分代码:

listview=new QListView(this);

listview->setViewMode(QListView::IconMode);

listview->setMovement(QListView::Static); 

listview->setIconSize(QSize(100,100));

listview->setGridSize(QSize(150,130));

listview->setGeometry(0,0,480,272);

listview->setResizeMode(QListView::Adjust); s1=new QStandardItem(QIcon(":/515.png"),"普通员工");

s2=newQStandardItem(QIcon(":/t01e28c73faf31c0d8c.jpg"),"领导");

s3=newQStandardItem(QIcon(":/520.png"),"huangling");

s4=newQStandardItem(QIcon(":/521.png"),"bailing"); 

s5=newQStandardItem(QIcon(":/518.png"),"jinling");

s6=newQStandardItem(QIcon(":/519.png"),"heiling"); 

slm=new QStandardItemModel(this);slm->appendRow(s1);

slm->appendRow(s2); 

slm->appendRow(s3);

slm->appendRow(s4);

slm->appendRow(s5);

slm->appendRow(s6);

listview->setModel(slm);

10.qt读取文件夹下所有文件

#include

#include

 int main(int argc, char *argv[])

 {

     QCoreApplicationapp(argc, argv);

     QDir dir;

     dir.setFilter(QDir::Files| QDir::Hidden | QDir::NoSymLinks);

     dir.setSorting(QDir::Size| QDir::Reversed);

 

     QFileInfoListlist = dir.entryInfoList();

     std::cout<< "     Bytes Filename" <

     for (inti = 0; i < list.size(); ++i) {

         QFileInfofileInfo = list.at(i);

         std::cout<< qPrintable(QString("%1 %2").arg(fileInfo.size(), 10)

                                                 .arg(fileInfo.fileName()));

         std::cout<< std::endl;

     }

     return 0;

}

QFileInfoList GetFileList(QString path)

{

    QDir dir(path);

    QFileInfoListfile_list = dir.entryInfoList(QDir::Files | QDir::Hidden | QDir::NoSymLinks);

    QFileInfoListfolder_list = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);

 

    for(int i = 0;i != folder_list.size(); i++)

    {

         QStringname = folder_list.at(i).absoluteFilePath();

         QFileInfoListchild_file_list = GetFileList(name);

         file_list.append(child_file_list);

    }

 

    returnfile_list;

}

11. QDir类来实现目录的遍历

 

void chakan(QString path){  

    QDir dir(path);  

   

   foreach(QFileInfo mfi ,dir.entryInfoList())  

    {  

     if(mfi.isFile())  

      {  

         qDebug()<< "File :" << mfi.fileName();  

      }else  

      {  

         if(mfi.fileName()=="." || mfi.fileName() == "..")continue;  

         qDebug() << "Entry Dir" << mfi.absoluteFilePath();  

         chakan(mfi.absoluteFilePath());  

      }  

    }  

  }

 

12.  实现多窗口切换,并从子窗口返回数据

http://blog.csdn.net/wubaigen/article/details/40787019

13. 单例模式

http://m.blog.csdn.net/article/details?id=51407248

http://blog.csdn.net/yuventus/article/details/6387026

14. 发布应用

Debug版本运行需要以下四个文件(与exe放在同一目录)  

Release版本运行需要以下四个文件(与exe放在同一目录)  

相应路径:

可以先把上述dll单独拷贝到一个文件夹中然后借助win下的MoleBox 打包软件便可生成独立运行文件,MoleBox下载地址:http://pan.baidu.com/s/1o60lXxS

下面我以打包一个HelloQt的deBug发布版为例

首先将上述Debug版本所需的dll拷贝到当前项目的HelloQt.exe目录下,然后运行MoleBox软件,设置如下:

注意:如果封包之后,点击执行发现出现”out of memory”情况,则请去网上换一个moleBox软件再试试,这个情况一般是moleBox软件的问题。

<参考源文件>

实测win8下安装使用QT4.8+qtcreator2.8.0<参考安装步骤>

【原创】【亲测可用】Qt4.8.5+QtCreator2.8.0傻瓜安装教程<参考配置步骤>

QtCreator + MinGW 在windows 下的调试<参考gdb调试器配置步骤>

http://blog.csdn.net/u010824946/article/details/42339941

 

按此方法仍会出现mingwm10.dll和libgcc_s_dw2-1.dll找不到,将这两个文件放到应用程序同一目录下。

15.获取IP地址、MAC地址等网卡信息,区分本地网卡、无线网卡和虚拟网卡

QStringWidget::getAdapterInfoWithQt()

{

    QStringstr=QString();

    QListinterfaceList=QNetworkInterface::allInterfaces();

 

    foreach(QNetworkInterfaceinterfaceItem,interfaceList)

    {

        if(interfaceItem.flags().testFlag(QNetworkInterface::IsUp)

                &&interfaceItem.flags().testFlag(QNetworkInterface::IsRunning)

                &&interfaceItem.flags().testFlag(QNetworkInterface::CanBroadcast)

                &&interfaceItem.flags().testFlag(QNetworkInterface::CanMulticast)

                &&!interfaceItem.flags().testFlag(QNetworkInterface::IsLoopBack)

                &&interfaceItem.hardwareAddress()!="00:50:56:C0:00:01"

                &&interfaceItem.hardwareAddress()!="00:50:56:C0:00:08")

        {

            QListaddressEntryList=interfaceItem.addressEntries();

            foreach(QNetworkAddressEntryaddressEntryItem,addressEntryList)

            {

                if(addressEntryItem.ip().protocol()==QAbstractSocket::IPv4Protocol)

                {

                    qDebug()<<"------------------------------------------------------------";

                    qDebug()<<"AdapterName:"<

                    qDebug()<<"AdapterAddress:"<

                    qDebug()<<"IPAddress:"<

                    qDebug()<<"IPMask:"<

                    returnaddressEntryItem.ip().toString();

                }

            }

        }

    }

 

    return0;

}

http://blog.csdn.net/caoshangpa/article/details/51073138

16. ‘tr' was not declared in this scope


 

QObject::tr();

 

17. gbk转unicode

QTextCodec *codec=QTextCodec::codecForName("GB2312");

QString str=codec->toUnicode(ch,strlen(ch));

label->setText(str);

http://david4383.blog.163.com/blog/static/3366036201291011032796/

Unicode

http://baike.baidu.com/link?url=o05KLLn9y0oOhpxISr8SHH1zPqrEIEohF1qUHkPPZFZf5-9U7kCYA_un1pQ0RXRU7LZWwSj956xmf3YQOnaorK

GBK

http://www.qqxiuzi.cn/zh/hanzi-gbk-bianma.php

18.添加库文件

INCLUDEPATH += -I../inc

LIBS += -L./ -ltermb

19.Qt中文乱码

在/usr/lib/fonts文件夹(QT_QWS_FONTDIR),拷贝一个字体进去,如 wqy-microhei.ttf,然后代码中设置

//编码设置

   QTextCodec *codec = QTextCodec::codecForName("UTF-8");

 

   QTextCodec::setCodecForTr(codec);

   //QTextCodec::setCodecForLocale(QTextCodec::codecForLocale());

   //QTextCodec ::setCodecForCStrings(QTextCodec::codecForLocale());

   QTextCodec::setCodecForLocale(codec);

   QTextCodec ::setCodecForCStrings(codec);

//字体设置

   QFont font("wqy-microhei",20);

   a.setFont(font);

 

http://www.cnblogs.com/M-Bing/p/3762597.html

QDateTime

20.IP地址正则表达式

表达式:((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))     

方式一:

   QRegExp rx = QRegExp("((25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))");

   QRegExpValidator *validator = new QRegExpValidator(rx, this)  

 

   lineEdit->setValidator(validator);

 

方式二:  

   lineEdit->setInput("000.000.000.000;0");

 

两种方式不能同时生效。   

 

http://www.cnblogs.com/olive987/p/5844501.html

 

21.setInputMask

This property holds the validation input mask.

If no mask is set, inputMask() returns an empty string.

Sets the QLineEdit's validation mask. Validators can be used instead of, or in conjunction with masks; see setValidator().

Unset the mask and return to normal QLineEdit operation by passing an empty string ("") or just calling setInputMask() with no arguments.

The table below shows the characters that can be used in an input mask. A space character, the default character for a blank, is needed for cases where a character is permitted but not required.

Character

Meaning

A

ASCII alphabetic character required. A-Z, a-z.

a

ASCII alphabetic character permitted but not required.

N

ASCII alphanumeric character required. A-Z, a-z, 0-9.

n

ASCII alphanumeric character permitted but not required.

X

Any character required.

x

Any character permitted but not required.

9

ASCII digit required. 0-9.

0

ASCII digit permitted but not required.

D

ASCII digit required. 1-9.

d

ASCII digit permitted but not required (1-9).

#

ASCII digit or plus/minus sign permitted but not required.

H

Hexadecimal character required. A-F, a-f, 0-9.

h

Hexadecimal character permitted but not required.

B

Binary character required. 0-1.

b

Binary character permitted but not required.

>

All following alphabetic characters are uppercased.

<

All following alphabetic characters are lowercased.

!

Switch off case conversion.

\

Use \ to escape the special characters listed above to use them as separators.

The mask consists of a string of mask characters and separators, optionally followed by a semicolon and the character used for blanks. The blank characters are always removed from the text after editing.

Examples:

Mask

Notes

000.000.000.000;_

IP address; blanks are _.

HH:HH:HH:HH:HH:HH;_

MAC address

0000-00-00

ISO Date; blanks are space

>AAAAA-AAAAA-AAAAA-AAAAA-AAAAA;#

License number; blanks are - and all (alphabetic) characters are converted to uppercase.

To get range control (e.g., for an IP address) use masks together with validators.

Access functions:

QString

inputMask () const

void

setInputMask ( const QString & inputMask )

22.GDB调试器已停止工作

http://qt-project.org/wiki/QtCreatorBuildGdb

下载Downloads中的GDB 7.5 binaries,文件名为qtcreator-gdb-7.4-MINGW32_NT-6.1-i686.tar.gz,用winRAR解压,构建套件将调试器设置为gdb-i686-pc-mingw32.exe 重启软件,即可。

23.SPlainTextEdit中SCrollBar置底

voidFormLog::init()

{

    QFile file("log.txt");

    file.open(QIODevice::ReadOnly);

    QTextStream text_stream(&file);

    ui->plainTextEdit_User->setPlainText(text_stream.readAll());

file.close();

QScrollBar *scrollbar = ui->plainTextEdit_User->verticalScrollBar();

    if(scrollbar)

    {

        scrollbar->setValue(scrollbar->maximum());

    }

}

 

注:FormLog必须先show才可以。

24. 日志

void myMessageOutput(QtMsgTypetype,const char *msg)

{

    QString text;

    QTextCodec *codec = QTextCodec::codecForName("UTF8");

    QString unidata = codec->toUnicode(msg);
 

    static QMutex mutex;

 

    mutex.lock();
 

    switch (type) {

 

    case QtDebugMsg:

 

        text = QString("Debug: ");

 

        fprintf(stderr, "Debug: %s\n", unidata.toLatin1().data());

 

        break;

 

    case QtWarningMsg:

 

        text = QString("Warning: ");

 

        fprintf(stderr, "Warning: %s\n", unidata.toLatin1().data());

 

        break;

 

    case QtCriticalMsg:

 

        text = QString("Critical: ");

 

        fprintf(stderr, "Critical: %s\n", unidata.toLatin1().data());

 

        break;

 

    case QtFatalMsg:

 

        text = QString("Fatal: ");

 

        fprintf(stderr, "Fatal: %s\n", unidata.toLatin1().data());

 

        abort();

 

    }

 


 

    QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd,hh:mm:ss");

 

    QString current_date = QString("%1").arg(current_date_time);

 

    QString message = QString("%1,%2,%3").arg(current_date).arg(text).arg(msg);
 

    QFile file("log.txt");

    file.open(QIODevice::WriteOnly | QIODevice::Append);

    QTextStream text_stream(&file);

 

    text_stream << message << "\r\n";

    file.flush();

    file.close();
 

    mutex.unlock();

 

}

 

int main(intargc,char *argv[])

{

       .................................

       qInstallMsgHandler(myMessageOutput);

       .................................

}

25. qt creator中添加子项目

首先在工程目录下添加各个文件夹,在文件夹中添加pri,cpp,h和ui文件,然后
pro文件中添加:
include (./文件夹路径/XXX.pri)
SOURCES += ./src/main.cpp
pri文件中:
DEPENDPATH += $$PWD
INCLUDEPATH += $$PWD
HEADERS +=
SOURCES +=
FORMS +=
这样就可以了

26.QLineEdit限制l输入为8位数字

  QValidator *validator=new QIntValidator(0,99999999,this); // 0-100 only accept number
  ui->lineEdit_Meter_Code_Init->setValidator(validator);
  ui->lineEdit_Meter_Code->setValidator(validator);

27. 判断QString含中文

    bool IsChinese(QString str)

    {

        bool b = str.contains(QRegExp("[\\x4e00-\\x9fa5]+"));

        if(b)

        {

            return true;

        }

        return false;

    }

28. 设置控件背景与字体颜色

ui->textEdit->setStyleSheet("background-color:White;");    
ui->textEdit->setTextColor(Qt::black);
ui->textEdit->append("红色字体 ");

29. QString符点数保留小数位

    QString str = QString::number(3.1415926,'f',2);

30. QString固定长度补0

str = QString("%1").arg(3.12,6,QChar('0'));

你可能感兴趣的:(qt)