Qt根据属性判断对象的类型

16 篇文章 1 订阅
4 篇文章 0 订阅

Qt 判断对象类型

Qt根据属性判断对象的类型

  • 在使用Qt的过程中偶尔有需求需要动态判断当前对象的类型,比如模板类中若对不同的类型有特殊处理,需要用到此功能,Qt的元对象系统提供了属性来进行判断
bool QObject::inherits(const char *className) const
Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false.
A class is considered to inherit itself.
Example:

  QTimer *timer = new QTimer;         // QTimer inherits QObject
  timer->inherits("QTimer");          // returns true
  timer->inherits("QObject");         // returns true
  timer->inherits("QAbstractButton"); // returns false

  // QVBoxLayout inherits QObject and QLayoutItem
  QVBoxLayout *layout = new QVBoxLayout;
  layout->inherits("QObject");        // returns true
  layout->inherits("QLayoutItem");    // returns true (even though QLayoutItem is not a QObject)

If you need to determine whether an object is an instance of a particular class for the purpose of casting it, consider using qobject_cast<Type *>(object) instead.
  • 实际使用过程中可以通过 inherits 或者 qobject_cast 转换然后判空来实现此功能
  • 示例:
	// 比如我需要判断一个窗口是QMainWindow 还是 QDialog
	QMainWindow* ptr = new QMainWindow();
	if (ptr->inherits("QMainWindow")) {
		// this is a QMainWindow
	} else if (ptr->inherits("QDialog")) {
		// this is a QDialog
	}
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值