Qt中QVariant的使用

发布于:2025-02-10 ⋅ 阅读:(44) ⋅ 点赞:(0)

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和label
    connect(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


网站公告

今日签到

点亮在社区的每一天
去签到