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

猜你喜欢

转载自blog.csdn.net/fengbingchun/article/details/130454199