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