Qt学习杂记
【查看UI文件生成的对应代码】
- 自动生成的ui.h文件
- Qt 5.14 -> Qt Widgets 相关的API介绍
- 自定义对象加上元属性:Q_OBJECT
class MyButton : public QPushButton
{
Q_OBJECT
public:
MyButton(QString text, QWidget *parent):QPushButton(qmove(text), parent)
{}
~MyButton();
}
- 对象树:参考Qt帮助手册Qt 5.14 ——Qt Core——Object Trees & Ownership
【信号与槽】
[static] QMetaObject::Connection QObject::connect(const QObject *sender,
const char *signal,
const QObject *receiver,
const char *method, Qt::ConnectionType type = Qt::AutoConnection)
- 示例1
QLabel *label = new QLabel;
QLineEdit *lineEdit = new QLineEdit;
QObject::connect(lineEdit, &QLineEdit::textChanged,
label, &QLabel::setText);
- 示例2
connect(ui->btn1, &QPushButton::clicked, this, [this]{
int value = ui->spin->value();
--value;
ui->spin->setValue(value);
} );
connect(ui->btn2, &QPushButton::clicked, this, [this]{
int value = ui->spin->value();
++value;
ui->spin->setValue(value);
} );
【QLable参考文档查看】
【QDebug】
qDebug("Hello %s", "world");
qDebug() << "这是调试";
- 默认将utf-8转为本地支持的解码,不产生乱码。
- 类似的有QFile,支持中文。
【QTextCode】
- 转码。
QTextCodec *codecForLocale()
QByteArray fromUnicode(const QString &str) const
QByteArray fromUnicode(QStringView str) const
- 示例
const char str[] = "小明";
QTextCodec *local = QTextCodec::codecForLocale();
std::cout << local->fromUnicode(str).constData() << std::endl;
【调试输出到文件】
QDebug::QDebug(QIODevice *device)
- QIODevice
QFile file("hello.txt");
if (!file.open(QIODevice::WriteOnly))
{
return false;
}
QDebug debug(&file);
debug << "error";
file.close;
【QString】
QString QString::arg(const QString &a, int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const
- 示例
QString i; // current file's number
QString total; // number of files to process
QString fileName; // current file's name
QString status = QString("Processing file %1 of %2: %3")
.arg(i).arg(total).arg(fileName);
- split使用
QStringList QString::split(const QString &sep,
QString::SplitBehavior behavior = KeepEmptyParts,
Qt::CaseSensitivity cs = Qt::CaseSensitive) const
QString str = "a,,b,c";
QStringList list1 = str.split(',');
// list1: [ "a", "", "b", "c" ]
QStringList list2 = str.split(',', QString::SkipEmptyParts);
// list2: [ "a", "b", "c" ]
【json处理】
- QJsonArray
- QJsonDocument
- QJsonObject
- QJsonParseError
- QJsonValue
- 重要的函数:
QJsonDocument fromJson(const QByteArray &json, QJsonParseError *error = nullptr)
QJsonObject object() const
QByteArray toJson() const
QJsonDocument(const QJsonArray &array)
QJsonDocument(const QJsonObject &object)
- 示例
QByteArray jsonJson = R"(
{
"name": "张三";
"age" : 69
}
)";
QJsonDocument document = QJsonDocument::fromJson(jsonJson);
QJsonObject object = document.object();
qDebug() << object["name"].toString() ; //object["name"]返回QJsonValue
//把Json对象转为字节数
QJsonDocument toByte(object);
qDebug()<< toByte.toJson();