1.使用QVariant實現不同類型數據的相加
方法:通過type函數返回數值的類型,然后通過setValue來構造一個QVariant類型的返回值。
函數:
QVariant mainPage::dataPlus(QVariant a, QVariant b)
{QVariant ret;if ((a.type() == QVariant::Int) && (b.type() == QVariant::Int)){ret.setValue(a.toInt() + b.toInt());}else if ((a.type() == QVariant::String) && (b.type() == QVariant::String)){ret.setValue(a.toString() + b.toString());}return ret;
}
調用:
qDebug() << dataPlus(10, 20).toInt();
qDebug() << dataPlus("hello ", "world!!!").toString();
2.獲取系統當前時間
//需求:獲取當前的日期QDate currentDateVal = QDate::currentDate();qDebug() << currentDateVal.toString("yyyy-MM-dd");//獲取當前的時間QTime currentTimeVal = QTime::currentTime();qDebug() << currentTimeVal.toString("H-mm-ss");//獲取當前日期和時間QDateTime currentDateAndTime = QDateTime::currentDateTime();qDebug() << currentDateAndTime.toString("yyyy-MM-dd H-mm-ss");
結果:
3.信號槽的使用
//關聯按鈕和lineedit和labelconnect(ui_.m_btn, &QPushButton::clicked, this, [=]() {QString imagePath = ":/img/fengjing.jpg";ui_.m_label->setPixmap(QPixmap(imagePath));ui_.m_lineEdit->setText(imagePath);qDebug() << "button slot is running..." << Qt::endl;});
結果:
4.定時器QTimer