qt基础

来源:互联网 发布:我国加工贸易现状知乎 编辑:程序博客网 时间:2024/05/16 15:20

qt使用问题记录


编译问题

qt自定义类没有加Q_OBJECT宏, 得清理工程然后qmake,重新编译。

自定义动态共享库export和import

    #if defined(QXMPP_BUILD)    #define QXMPP_EXPORT Q_DECL_EXPORT    #else    #define QXMPP_EXPORT Q_DECL_IMPORT    #endif

qt常用功能

qt应用图标

#RC_ICONS = youApp.ico

关闭窗口自动销毁类
this->setAttribute(Qt::WA_DeleteOnClose, true);
设置图标为系统关闭图标
button->setIcon(this->style()->standardIcon(QStyle::StandardPixmap(1)));
Q_UNUSED(option) //声明该变量没有使用

绘制是后去该项目是否被选中

`if(option->state & QStyle::State_Selected)`

hash生成类

QCryptographicHash 

设置qt应用的类型 例如windows, winxp

    QStyleFactory::keys()                               获取所有的 支持的风格类型    void QApplication::​setStyle(QStyle * style) 应用该风格    QStyle * QApplication::​setStyle(const QString & style)   

qt换肤功能

    QString Style::getStylesheet(const QString &filename)    {    QFile file(filename);    if (!file.open(QFile::ReadOnly | QFile::Text))     {    qWarning() << "Stylesheet " << filename << " not found";    return QString();    }    return resolve(file.readAll());    }

splitter 设置第几个控件可以伸缩

ui->splitter->setStretchFactor(0, 1);               //设置第一个窗体可以伸缩

windows 下设置窗体透明

1.设置背景色实现部件窗体透明

`QPushButton{background-color: rgba(255, 255, 255, 100)}`

2.整个窗体的透明度设置

setWindowOpacity(0.3);

3.设置窗体透明但是其中的部件不透明

    setWindowFlags(Qt::FramelessWindowHint);    setAttribute(Qt::WA_TranslucentBackground, true);

在c++文件中包含c语言头

#ifdef _cplusplus   //是否在cpp文件中extern "C"{/*....*/}#endif

自定义输出信息 qDebug()

1.重写输出函数

    #include <qapplication.h>    #include <stdio.h>    #include <stdlib.h>    void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)    {    QByteArray localMsg = msg.toLocal8Bit();    switch (type) {    case QtDebugMsg:    fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);    break;    case QtWarningMsg:    fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);    break;    case QtCriticalMsg:    fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);    break;    case QtFatalMsg:    fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);    abort();    }    }    int main(int argc, char **argv)    {    qInstallMessageHandler(myMessageOutput);    QApplication app(argc, argv);    ...    return app.exec();    }

2使用qt自带的函数注册输出格式

    qSetMessagePattern("[%{time h:mm:ss.zzz} %{if-debug}Debug%{endif}%{if-warning}Waring%{endif}%{if-critical}            Critical%{endif}%{if-fatal}Fatal%{endif}] %{file}:%{line} : %{message}");

QMetaObject::invokeMethod()

Qt 提供了一个优雅清晰的解决方案:我们在线程的事件队列中加入一个事件,然后在事件处理函数中调用我们所关心的函数。显然这需要线程有一个事件循环。这种机制依赖于 moc 提供的反射:因此,只有信号、槽和使用Q_INVOKABLE宏标记的函数可以在另外的线程中调用。
QMetaObject::invokeMethod()静态函数会这样调用:

QMetaObject::invokeMethod(object, "methodName", Qt::QueuedConnection, Q_ARG(type1, arg1), Q_ARG(type2, arg2)); 

注意,上面函数调用中出现的参数类型都必须提供一个公有构造函数,一个公有的析构函数和一个公有的复制构造函数,并且要使用qRegisterMetaType()函数向 Qt 类型系统注册。

Q_FLAGS宏的使用

    Q_FLAGS(Action Actions)    If you want to use QFlags for your own enum types, use the Q_DECLARE_FLAGS() and Q_DECLARE_OPERATORS_FOR_FLAGS().    Example:    class MyClass    {    public:    enum Option {    NoOptions = 0x0,    ShowTabs = 0x1,    ShowAll = 0x2,    SqueezeBlank = 0x4    };    Q_DECLARE_FLAGS(Options, Option)    ...    };    Q_DECLARE_OPERATORS_FOR_FLAGS(MyClass::Options)    You can then use the MyClass::Options type to store combinations of MyClass::Option values.    The Q_DECLARE_FLAGS() macro does not expose the flags to the meta-object system, so they cannot be used by Qt Script     or edited in Qt Designer.To make the flags available for these purposes, the Q_FLAG() macro must be used:    Q_FLAG(Options)  
最新代码从5.5使用Q_FLAG , 和Q_ENUM()宏

加速键 和 伙伴关系

QLabel 提供加速功能, 编辑QLable 文本内容为 &Native,加速键对应 ctrl+N, 如果含有中文编辑内容为 “编辑(&N)".使用 QLabel的setBUddy设置伙伴关系, 设置后按相应加速键其伙伴就可以自动获取光标。

.pro 文件使用

    TEMPLATE = app / lib   app/ .dll        CONFIG   += c++11          //支持c++11    CONFIG   += link_pkgconfig    DEFINES  += LOG_TO_FILE    DESTDIR =../               //生成文件路径    TARGET  = file             //目标文件名称    QMAKE_CXXFLAGS += -Wno-unused-parameter -Wno-unused-variable  //消除编译时没有使用参数和变量的警告

Qt 国际化翻译

1. 在源码中需要显示的字符串要用tr()函数设置。2. 更改项目文件 .pro文件, 在文件后加入  TRANSLATIONS = myI18N_zh_CN.ts  3. 运行 lupdate myI18N.pro  会生成 .ts文件4. 使用 Qt linguist 打开.ts 文件然后逐个翻译。5. lrelease muI18N.pro生成.qm文件 6. 使用.qm文件,    QTranslator translator;    tanslator.load("../myI18N/myI18N_zh_CN.qm");    a.installTranslator(&translator); 使用翻译文件。-----

.pri文件自动生成 .qm

在.pro文件中加入include(translations/i18n.pri)i18n.pri 文件源码如下:
    # For autocompiling qm-files.    TRANSLATIONS = translations/zh.ts \    translations/uk.ts    #rules to generate ts      QMAKE_LUPDATE = $$[QT_INSTALL_BINS]/lupdate.exe    #limitation: only on ts can be generated    updatets.name = Creating or updating ts-files...    updatets.input = _PRO_FILE_    updatets.output = $$TRANSLATIONS    updatets.commands = $$QMAKE_LUPDATE ${QMAKE_FILE_IN}    updatets.CONFIG += no_link no_clean    QMAKE_EXTRA_COMPILERS += updatets    #rules for ts->qm    isEmpty(QMAKE_LRELEASE) {    win32: QMAKE_LRELEASE = $$[QT_INSTALL_BINS]/lrelease.exe    else:  QMAKE_LRELEASE = $$[QT_INSTALL_BINS]/lrelease    }    updateqm.name = Compiling qm-files...    updateqm.input = TRANSLATIONS    updateqm.output = ${QMAKE_FILE_PATH}/${QMAKE_FILE_BASE}.qm    updateqm.commands = $$QMAKE_LRELEASE ${QMAKE_FILE_IN} -qm ${QMAKE_FILE_PATH}/${QMAKE_FILE_BASE}.qm    updateqm.CONFIG += no_link  no_clean target_predeps    QMAKE_EXTRA_COMPILERS += updateqm    # Release all the .ts files at once    updateallqm = $$QMAKE_LRELEASE -silent $$TRANSLATIONS

格式无关读取图片

    QByteArray m_photo = vCard.photo();    QBuffer buffer;    buffer.setData(m_photo);    buffer.open(QIODevice::ReadOnly);    QImageReader imageReader(&buffer);    QImage image = imageReader.read();

跨线程调用类或结构体

    qRegisterMetaType<QXmppMessage>("QXmppMessage");    qRegisterMetaType<QXmppPresence>("QXmppPresence");    This example registers the class MyClass:    qRegisterMetaType<MyClass>("MyClass");    This function is useful to register typedefs so they can be used by QMetaProperty, or in QueuedConnections

使用窗体绘制函数render生成图片

QPixmap pixmap(QSize());QPainter painter(&pixmap);widget->render(&painter);

qt加载flash

1.在pro文件中加入 QT += axcontainer
2.加入头文件
3.加入代码

QAxWidget object;object.setControl("{d27cdb6e-ae6d-11cf-96b8-444553540000}");object.dynamicCall("LoadMovie(long, QString)", 0, "J:\\flash2509.swf");object.show();

数据库操作

qt支持数据库的数据类行查看 Data Types for Qt-supported Database Systems

列出所有的支持的数据库驱动

    QStringList drivers=QSqlDatabase::drivers;创建数据库连接    QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");    db.setHostName("acidalia");    db.setDatabaseName("customdb");    db.setUserName("mojito");    db.setPassword("J0a1m8");    bool ok = db.open();    QSqlQuery query;    query.exec("INSERT INTO employee (id, name, salary) "               "VALUES (1001, 'Thad Beaumont', 65000)");存在多个连, 查询时要指定使用哪个链接    QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL", "connect1");    db.setHostName("acidalia");    db.setDatabaseName("customdb");    db.setUserName("mojito");    db.setPassword("J0a1m8");    bool ok = db.open();    //创建数据表    db.exec("create table IF NOT EXISTS history(id varchar, messagetype INTEGER, sendername varchar, message varchar, datetime INTEGER)");    QSqlQuery query(db);    query.exec("INSERT INTO employee (id, name, salary) "               "VALUES (1001, 'Thad Beaumont', 65000)");

Qt智能指针

QPointerQSharedPointerQWeakPointerQScopedPointerQScopedArryPointerQShareDataPointerQExplicitlyShareDataPointerstd::auto_ptrstd::shared_ptrstd::weak_ptrsta::unique_ptr

文字和输入处理

QTextEdit 输入框可以插入图片

1.重写canInsertMimeData(const QMimeData *source) const;方法方法实现如下

bool MyTextEdit::canInsertFromMimeData( const QMimeData *source ) const{    if (source->hasImage())        return true;    else        return QTextEdit::canInsertFromMimeData(source);}

2.重写insertFormMimeData(const QMimeData *source);实现如下

void MyTextEdit::insertFromMimeData( const QMimeData *source ){    if (source->hasImage())    {        static int temp_picture_number=0;        QImage image= qvariant_cast<QImage>(source->imageData());        image.save(QString("temp_picture/mypic%1.png").arg(temp_picture_number));        int width=400, heigth=200;        if(image.size().width()<width)        {            width=image.size().width();        }        if(image.size().height()<heigth)        {            heigth=image.size().height();        }        this->append(QString("<img width=%3 height=%2 src=temp_picture/mypic%1.png>").arg(temp_picture_number).arg(heigth).arg(width));        temp_picture_number++;    }    QTextEdit::insertFromMimeData(source);}

QTextDocument 绘制富文本

QAbstractTextDocumentLayout::PaintContext ctx;QAbstractTextDocumentLayout::Selection sel;if (hasSelection()){sel.cursor = QTextCursor(doc);sel.cursor.setPosition(getSelectionStart());sel.cursor.setPosition(getSelectionEnd(), QTextCursor::KeepAnchor);}const QColor selectionColor = QColor::fromRgbF(0.23, 0.68, 0.91);sel.format.setBackground(selectionColor.lighter(selectionHasFocus ? 100 : 160));sel.format.setForeground(selectionHasFocus ? Qt::white : Qt::black);ctx.selections.append(sel);ctx.palette.setColor(QPalette::Text, color);QTextDocument* doc = nullptr; // draw textdoc->documentLayout()->draw(painter, ctx);

文本自动加省略

QFontMetrics metrics = QFontMetrics(QFont("宋体", 9 , QFont::Bold));         //设置字体的宽度和大小QString elidedText = metrics.elidedText(bindingData?(bindingData->Name):(bindingRoomDta->RoomName), Qt::ElideRight, width); // 太长添加省略号

自定义隐式共享

#include <QSharedData>#include <QString>class EmployeeData : public QSharedData{  public:    EmployeeData() : id(-1) { }    EmployeeData(const EmployeeData &other)        : QSharedData(other), id(other.id), name(other.name) { }    ~EmployeeData() { }    int id;    QString name;};class Employee{  public:    Employee() { d = new EmployeeData; }    Employee(int id, QString name) {        d = new EmployeeData;        setId(id);        setName(name);    }    Employee(const Employee &other)          : d (other.d)    {    }    void setId(int id) { d->id = id; }    void setName(QString name) { d->name = name; }    int id() const { return d->id; }    QString name() const { return d->name; }  private:    QSharedDataPointer<EmployeeData> d;}; 

qt 加载外部字体

int fontId=QFontDatabase::addApplicationFont(":/Font/fontawesome-webfont");QStringList fontFamilies=QFontFatabase::applicationFontFamilies(fontId);QFont font;font.setFamily(fontFamilies.at(0));font.setPointSize(20);

QTreeView

设置列表可以多选
ui->listView->setSelectionMode(QAbstractItemView::ExtendedSelection);

元对象系统

To use the type T in QVariant, using Q_DECLARE_METATYPE() ;
Adding a Q_DECLARE_METATYPE() makes the type known to all template based functions, including QVariant. Note that if you intend to use the type in queued signal and slot connections or in QObject’s property system, you also have to call qRegisterMetaType() since the names are resolved at runtime.

This examplestruct

MyStruct  {int i;...};Q_DECLARE_METATYPE(MyStruct)  This example shows a typical use case of Q_DECLARE_METATYPE():struct MyStruct{int i;...};Q_DECLARE_METATYPE(MyStruct)If MyStruct is in a namespace, the Q_DECLARE_METATYPE() macro has to be outside the namespace:namespace MyNamespace{...}Q_DECLARE_METATYPE(MyNamespace::MyStruct)Since MyStruct is now known to QMetaType, it can be used in QVariant:MyStruct s;QVariant var;var.setValue(s); // copy s into the variant...// retrieve the valueMyStruct s2 = var.value<MyStruct>();

This function is useful to register typedefs so they can be used by QMetaProperty, or in QueuedConnections
typedef QString CustomString;

qRegisterMetaType<CustomString>("CustomString");

Q_DISABLE_COPY(WNavigationTar)  //声明没有拷贝构造函数和=运算符 //注册属性Q_PROPERTY(QColor currentItemColor READ currentItemColor WRITE setCurrentItemColor)Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize)Q_PROPERTY(int itemSpacing READ itemSpacing WRITE setItemSpacing)

Q_ENUMS(Direction Error State) 声明后可以在属性里面使用

字符串

QLatin1String

 This includes the copy constructor, the assignment operator, the comparison operators, and various other functions such as insert(), replace(), and indexOf(). These functions are usually optimized to avoid constructing a QString object for the const char * data. For example, assuming stris a QString,if (str == QLatin1String("auto")        || str == QLatin1String("extern")        || str == QLatin1String("static")        || str == QLatin1String("register") {    ...}可以加快速度;QString str("ss");  str.insert(QLatin1String("fn"));   //可以加快速度

QStringLiteral

QStringLiteral(":/qss/login.qss")      //存储字符串到objec里, 初始化不需要转码和分配内存.

子窗体设置style背景色不能显示

setAttribute(Qt::WA_StyledBackground);  //设置窗体显示以style显示

QSharedPointer QShareDate 隐士共享

#include <QSharedData>#include <QString>class EmployeeData : public QSharedData{  public:    EmployeeData() : id(-1) { }    EmployeeData(const EmployeeData &other)        : QSharedData(other), id(other.id), name(other.name) { }    ~EmployeeData() { }    int id;    QString name;};class Employee{  public:    Employee() { d = new EmployeeData; }    Employee(int id, QString name) {        d = new EmployeeData;        setId(id);        setName(name);    }    Employee(const Employee &other)          : d (other.d)    {    }    void setId(int id) { d->id = id; }    void setName(QString name) { d->name = name; }    int id() const { return d->id; }    QString name() const { return d->name; }  private:    QSharedDataPointer<EmployeeData> d;};

在linux下创建qt桌面图标

[Desktop Entry]Type=ApplicationExec=/home/bjm/Qt5.6.2/Tools/QtCreator/bin/qtcreatorName=Qt Creator (Community)GenericName=The IDE of choice for Qt development.Icon=QtProject-qtcreatorTerminal=falseCategories=Development;IDE;Qt;MimeType=text/x-c++src;text/x-c++hdr;text/x-xsrc;application/x-designer;application/vnd.qt.qmakeprofile;application/vnd.qt.xml.resource;text/x-qml;text/x-qt.qml;text/x-qt.qbs;

QFileIconProvider 获取文件图标

获取文件夹图标:

QFileIconProvider iconProvider;QIcon icon=iconProvider.icon(QFileIconProvider::Folder);

Qt获取屏幕分辨率

QApplication::desktop

Qt 常用宏

ctkServiceReferencePrivate * d_ptr;Q_DECLARE_PRIVATE(ctkServiceReference)   //声明私有数据Q_DECLARE_METATYPE(ctkServiceReference)  //告知元对象系统该类型

Qt 操作时间 datetime

sqlite 操作时间sqlQuery.exec("create table if not exists Test(id int, time datetime)");model->setQuery(QString("select * from Test where time <= '2017-03-20 18::18::43'"));

创建单实例应用

 QString serverName = QCoreApplication::applicationName();    QLocalSocket socket;    socket.connectToServer(serverName);    if (socket.waitForConnected(500)) {        QTextStream stream(&socket);        stream << m_initialUrl;        stream.flush();        socket.waitForBytesWritten();        return;    }#if defined(Q_OS_OSX)    QApplication::setQuitOnLastWindowClosed(false);#else    QApplication::setQuitOnLastWindowClosed(true);#endif    m_localServer = new QLocalServer(this);    connect(m_localServer, SIGNAL(newConnection()),            this, SLOT(newLocalSocketConnection()));    if (!m_localServer->listen(serverName)) {        if (m_localServer->serverError() == QAbstractSocket::AddressInUseError            && QFile::exists(m_localServer->serverName())) {            QFile::remove(m_localServer->serverName());            m_localServer->listen(serverName);        }    }

查看数据表字段信息

QString("PRAGMA table_info(%1)").arg(tableName);

qwebview 不能显示百度

把 qt-create中的 ssleay32.dll 和 libeay32.dll 复制到 qt sdk的 bin目录下面

QT MSVC中文乱码

在要编译带有中文的文件中加入 下面语句:#if _MSC_VER >= 1600#pragma execution_character_set("utf-8")  #endif 

Qt Windows Extras使用

QWinTaskbarButton *button = new QWinTaskbarButton(&w);button->setWindow(w.windowHandle());button->setOverlayIcon(QIcon(":/menuImage/alarm.png"));QWinTaskbarProgress *progress = button->progress();progress->setVisible(true);progress->setValue(50);

QT windows 程序崩溃调试

程序难免会出现异常崩溃,这时我们不仅要实时记录数据,以防止出现异常崩溃,而且还要能够捕捉所发生的异常。捕捉异常时会产生dump文件,以备对异常调试的可查;还要添加头文件和库文件。   #include <Windows.h>   #include "DbgHelp.h"   LIBS += -ldbghelp   在main函数中调用回调函数 SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);static LONG ApplicationCrashHandler(EXCEPTION_POINTERS *pException){    //And output crash information    EXCEPTION_RECORD *record = pException->ExceptionRecord;    QString errCode(QString::number(record->ExceptionCode, 16));    QString errAddr(QString::number((uint)record->ExceptionAddress, 16));    QString errFlag(QString::number(record->ExceptionFlags, 16));    QString errPara(QString::number(record->NumberParameters, 16));    qDebug()<<"errCode: "<<errCode;    qDebug()<<"errAddr: "<<errAddr;    qDebug()<<"errFlag: "<<errFlag;    qDebug()<<"errPara: "<<errPara;    //Create the dump file    HANDLE hDumpFile = CreateFile((LPCWSTR)QString("../bin_vs/crash.dmp").utf16(),             GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);    if(hDumpFile != INVALID_HANDLE_VALUE) {        MINIDUMP_EXCEPTION_INFORMATION dumpInfo;        dumpInfo.ExceptionPointers = pException;        dumpInfo.ThreadId = GetCurrentThreadId();        dumpInfo.ClientPointers = TRUE;        MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(),hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);        CloseHandle(hDumpFile);    }    return EXCEPTION_EXECUTE_HANDLER;}

判断一个字符串是否有汉字

QString str;   bool b = str.contains(QRegExp("[\\x4e00-\\x9fa5]+"));   if(b)   {       //存在中文   }   

自定义QT标题栏

setAttribute(Qt::FramelessWindowHint)设置窗体去除边框  setAttribute(Qt::WindowMinimizeButtonHint)在窗口最小化是点击任务栏可以显示出原窗口

QFontMetrics

构建一个测量字符串占用像素点的类。

QTableView 使用

tableview 头自适应窗体宽度

mTableServiceList->verticalHeader()->setResizeMode(QHeaderView::Stretch);

获取全局鼠标

QApplication::mouseButtons()

qt获取宏名称

Qt::qt_getEnumName(Qt::ExtraButton1);

右值

函数参数 引用变量声明为 const 类型 可以绑定 右值类型, 不然只能绑定左值类型

QT5编程入门学习

Qt5新特性


在QT5中新的信号和槽的关联使用

connect(sender, &Sender::valueChanged, reciver, &Reciver::showValue)

支持编译时检查, 支持相容类型自动转化, 可以连接任何函数不用声明 slot

如果信号和槽有重载:

connect(sender, static_cast<void(QSpinBox::*) (int)> (&QSpinBox::valueChanged)) , this, &MainWindow::onSpinBoxChanged);

c++11支持, 在.pro中增加 CONFIG += c++11

constexpr 用于向编译器指出, 函数或变量在编译时运算。 QT5中使用 Q_DECL_CONSTEXPRstatic_assert 静态断言, 编译时检测一些条件是否成立  Q_STATIC_ASSERToverride  修饰函数, 函数必须覆盖父类的函数,  Q_DECL_OVERRIDEvoid MyWidget::mouseMoveEvent() Q_DECL_OVERRIDE       final 打断virtual的传播 如果一个虚函数被final修饰所有的子类都不能覆盖该函数, Q_DECL_FINALdelete 显示禁止c++编译器生成代码, 被修饰的函数不能被调用。 Q_DECL_DELETE

Lambda 表达式: Lambda表达式就是匿名函数,。

connect(sender, &StringDialog::stringChanged, [=](QString str)) {if(str == "qt") {} else {}});

Lambad 表达式引入符:

  1. [] 不捕获任何局部变量
  2. [=] 以传值的方式捕获外部变量
  3. [&] 以引用的方式捕获外部变量
  4. [x, &y] x传值捕获, y引用捕获
  5. [=, &x] x引用捕获, 其他传值捕获
  6. [&, x] x传值捕获, 其它引用捕获

[a, &str]->QString{} 传值捕获a, 引用捕获str, 返回值是QString。

带默认参数的槽函数:

connect(sender, &sender::signal, [](){ pushButton->anumateClick });

QML 语法

  1. import 导入qt quick模块
  2. object , property

    Rectange{width: 100heigth: 100}
  3. 布局 anchors.centerIn 使子对象处于福对象的中心。

  4. 注射 /* */ or //
  5. 表达式 : Item { width:100 * 3 heigth: 50 + 22 }
    绑定属性, 该属性会根据表达式的值自动更新。

    Item {    width:300    Rectange {    width:parent.width - 50    }}
  6. 调试 : console.log("矩阵颜色", color)

原创粉丝点击