qt自定义类没有加Q_OBJECT宏, 得清理工程然后qmake,重新编译。
自定义动态共享库export和import
#if defined(QXMPP_BUILD)
#define QXMPP_EXPORT Q_DECL_EXPORT
#else
#define QXMPP_EXPORT Q_DECL_IMPORT
#endif
#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);
#ifdef _cplusplus //是否在cpp文件中
extern "C"{
/*....*/
}
#endif
1.重写输出函数
#include
#include
#include
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}");
Qt 提供了一个优雅清晰的解决方案:我们在线程的事件队列中加入一个事件,然后在事件处理函数中调用我们所关心的函数。显然这需要线程有一个事件循环。这种机制依赖于 moc 提供的反射:因此,只有信号、槽和使用Q_INVOKABLE宏标记的函数可以在另外的线程中调用。
QMetaObject::invokeMethod()静态函数会这样调用:
QMetaObject::invokeMethod(object, "methodName", Qt::QueuedConnection, Q_ARG(type1, arg1), Q_ARG(type2, arg2));
注意,上面函数调用中出现的参数类型都必须提供一个公有构造函数,一个公有的析构函数和一个公有的复制构造函数,并且要使用qRegisterMetaType()函数向 Qt 类型系统注册。
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设置伙伴关系, 设置后按相应加速键其伙伴就可以自动获取光标。
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 //消除编译时没有使用参数和变量的警告
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); 使用翻译文件。
-----
在.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");
qRegisterMetaType("QXmppPresence");
This example registers the class MyClass:
qRegisterMetaType("MyClass");
This function is useful to register typedefs so they can be used by QMetaProperty, or in QueuedConnections
QPixmap pixmap(QSize());
QPainter painter(&pixmap);
widget->render(&painter);
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)");
QPointer
QSharedPointer
QWeakPointer
QScopedPointer
QScopedArryPointer
QShareDataPointer
QExplicitlyShareDataPointer
std::auto_ptr
std::shared_ptr
std::weak_ptr
sta::unique_ptr
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(source->imageData());
image.save(QString("temp_picture/mypic%1.png").arg(temp_picture_number));
int width=400, heigth=200;
if(image.size().width()append(QString("").arg(temp_picture_number).arg(heigth).arg(width));
temp_picture_number++;
}
QTextEdit::insertFromMimeData(source);
}
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 text
doc->documentLayout()->draw(painter, ctx);
QFontMetrics metrics = QFontMetrics(QFont("宋体", 9 , QFont::Bold)); //设置字体的宽度和大小
QString elidedText = metrics.elidedText(bindingData?(bindingData->Name):(bindingRoomDta->RoomName), Qt::ElideRight, width);
// 太长添加省略号
#include
#include
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 d;
};
int fontId=QFontDatabase::addApplicationFont(":/Font/fontawesome-webfont");
QStringList fontFamilies=QFontFatabase::applicationFontFamilies(fontId);
QFont font;
font.setFamily(fontFamilies.at(0));
font.setPointSize(20);
设置列表可以多选
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 value
MyStruct s2 = var.value();
This function is useful to register typedefs so they can be used by QMetaProperty, or in QueuedConnections
typedef QString CustomString;
qRegisterMetaType
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) 声明后可以在属性里面使用
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 str
is a QString,
if (str == QLatin1String("auto")
|| str == QLatin1String("extern")
|| str == QLatin1String("static")
|| str == QLatin1String("register") {
...
}
可以加快速度;
QString str("ss"); str.insert(QLatin1String("fn")); //可以加快速度
QStringLiteral(":/qss/login.qss") //存储字符串到objec里, 初始化不需要转码和分配内存.
setAttribute(Qt::WA_StyledBackground); //设置窗体显示以style显示
#include
#include
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 d;
};
[Desktop Entry]
Type=Application
Exec=/home/bjm/Qt5.6.2/Tools/QtCreator/bin/qtcreator
Name=Qt Creator (Community)
GenericName=The IDE of choice for Qt development.
Icon=QtProject-qtcreator
Terminal=false
Categories=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 iconProvider;
QIcon icon=iconProvider.icon(QFileIconProvider::Folder);
QApplication::desktop
ctkServiceReferencePrivate * d_ptr;
Q_DECLARE_PRIVATE(ctkServiceReference) //声明私有数据
Q_DECLARE_METATYPE(ctkServiceReference) //告知元对象系统该类型
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);
把 qt-create中的 ssleay32.dll 和 libeay32.dll 复制到 qt sdk的 bin目录下面
在要编译带有中文的文件中加入 下面语句:
#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif
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);
程序难免会出现异常崩溃,这时我们不仅要实时记录数据,以防止出现异常崩溃,而且还要能够捕捉所发生的异常。
捕捉异常时会产生dump文件,以备对异常调试的可查;还要添加头文件和库文件。
#include
#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: "<
QString str;
bool b = str.contains(QRegExp("[\\x4e00-\\x9fa5]+"));
if(b)
{
//存在中文
}
setAttribute(Qt::FramelessWindowHint)设置窗体去除边框
setAttribute(Qt::WindowMinimizeButtonHint)在窗口最小化是点击任务栏可以显示出原窗口
构建一个测量字符串占用像素点的类。
tableview 头自适应窗体宽度
mTableServiceList->verticalHeader()->setResizeMode(QHeaderView::Stretch);
QApplication::mouseButtons()
###qt获取宏名称
Qt::qt_getEnumName(Qt::ExtraButton1);
函数参数 引用变量声明为 const 类型 可以绑定 右值类型, 不然只能绑定左值类型
####Qt5新特性
在QT5中新的信号和槽的关联使用
connect(sender, &Sender::valueChanged, reciver, &Reciver::showValue)
支持编译时检查, 支持相容类型自动转化, 可以连接任何函数不用声明 slot
如果信号和槽有重载:
connect(sender, static_cast (&QSpinBox::valueChanged)) ,
this, &MainWindow::onSpinBoxChanged);
c++11支持, 在.pro中增加 CONFIG += c++11
constexpr 用于向编译器指出, 函数或变量在编译时运算。 QT5中使用 Q_DECL_CONSTEXPR
static_assert 静态断言, 编译时检测一些条件是否成立 Q_STATIC_ASSERT
override 修饰函数, 函数必须覆盖父类的函数, Q_DECL_OVERRIDE
void MyWidget::mouseMoveEvent() Q_DECL_OVERRIDE
final 打断virtual的传播 如果一个虚函数被final修饰所有的子类都不能覆盖该函数, Q_DECL_FINAL
delete 显示禁止c++编译器生成代码, 被修饰的函数不能被调用。 Q_DECL_DELETE
Lambda 表达式: Lambda表达式就是匿名函数,。
connect(sender, &StringDialog::stringChanged, [=](QString str)) {
if(str == "qt") {
} else {}
});
Lambad 表达式引入符:
[a, &str]->QString{}
传值捕获a, 引用捕获str, 返回值是QString。
带默认参数的槽函数:
connect(sender, &sender::signal, [](){ pushButton->anumateClick });
import 导入qt quick模块
object , property
Rectange{
width: 100
heigth: 100
}
布局 anchors.centerIn
使子对象处于福对象的中心。
注射 /* */ or //
表达式 : Item { width:100 * 3 heigth: 50 + 22 }
绑定属性, 该属性会根据表达式的值自动更新。
Item {
width:300
Rectange {
width:parent.width - 50
}
}
调试 : console.log("矩阵颜色", color)