Qt中QDebug的使用

      QDebug类为调试信息(debugging information)提供输出流。它的声明在<QDebug>中,实现在Core模块中。将调试或跟踪信息(debugging or tracing information)写出到device, file, string or console时都会使用QDebug。

      此类的成员函数参考:https://doc.qt.io/qt-6/qdebug.html
      通常情况下,调用qDebug()函数获取调试信息
      qDebug()函数返回QDebug对象。QDebug格式化输出会自动在参数之间添加空格,并在QString、QChar参数周围添加引号。可以通过space()、nospace()和quote()、noquote()方法来调整这些选项。
      将自定义类型(custom types)写入流:可以将许多标准类型写入QDebug对象,Qt提供对大多数Qt值类型的支持。若要添加对自定义类型的支持,需要实现流操作符(streaming operator)。

      以下为测试代码:

namespace {

typedef struct {
	long x, y, z;
} Coordinate;

QDebug operator<<(QDebug debug, const Coordinate& c)
{
	// QDebugStateSaver limits changes to the formatting to the current scope
	QDebugStateSaver saver(debug);
	debug.nospace() << '(' << c.x << ", " << c.y << ", " << c.z << ')';

	return debug;
}

} // namespace

int test_qdebug_1()
{
	// qDebug(const char *message, ...):与C的printf(const char * format, ...)函数类似
	qDebug("current date: %d:%d:%d", QDate::currentDate().year(), QDate::currentDate().month(), QDate::currentDate().day());
	printf("current date: %d:%d:%d\n", QDate::currentDate().year(), QDate::currentDate().month(), QDate::currentDate().day());

	qDebug() << "Date:" << QDate::currentDate();

	QString s("beijing");
	qDebug() << "s:" << s;

	QByteArray ba("haidian");
	qDebug() << "ba:" << ba;

	// 注意以下两条语句输出的差异
	qDebug() << "Types:" << QString("String") << QChar('x') << QRect(0, 10, 50, 40);
	qDebug().nospace().noquote() << "Types:" << QString("String") << QChar('x') << QRect(0, 10, 50, 40);

	// 将自定义类型写入流
	Coordinate c = { 10, 20, 30 };
	qDebug() << "Coordinate:" << c;

	return 0;
}

      执行结果如下图所示:

      GitHubhttps://github.com/fengbingchun/Qt_Test

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值