通过QObjectList可以访问ui界面的控件的名字,找到名字后就可以实现一些其它的功能
ui界面如下
#include "testqt.h"
#include <QDebug>
testqt::testqt(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
QObjectList cs = this->children();//children()返回的是所有子节点,此时返回的是widget下的控件
for (int i = 0; i < cs.size(); i++)
{
qDebug() << cs[i]->objectName();
}
}
结果如下
将ui界面中控件的名字都打印了出来,我将继续在ui界面上添加一个widget,并且在widget里面添加一个button和一个label,如下
结果如下
也就是说objectName()
只能访问子节点的名字,不能递归访问子节点的子节点的控件。
#include "testqt.h"
#include <QDebug>
testqt::testqt(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
QObjectList cs = this->children();//访问当前子节点控件
for (int i = 0; i < cs.size(); i++)
{
qDebug() << cs[i]->objectName();
}
qDebug() << endl;
QObjectList gs = ui.widget->children();
for (int i = 0; i < gs.size(); i++)
{
qDebug() << gs[i]->objectName();
}
}
我们可以写一个函数来递归打印所有节点
#include "testqt.h"
#include <QDebug>
static QObject *PrintName(QObject *obj)
{
QObjectList cs = obj->children();
if (!obj)//为NULL就退出
{
return NULL;
}
qDebug() << obj->objectName();
if (cs.size() <= 0)
{
return NULL;
}
for (int i = 0; i < cs.size(); i++)
{
PrintName(cs[i]);
}
}
testqt::testqt(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
QObjectList cs = this->children();//访问当前子节点控件
PrintName(this);
qDebug() << "*******************";
for (int i = 0; i < cs.size(); i++)
{
qDebug() << cs[i]->objectName();
}
//qDebug() << endl;
QObjectList gs = ui.widget->children();
for (int i = 0; i < gs.size(); i++)
{
qDebug() << gs[i]->objectName();
}
}
对QLineEdit会多遍历出一个名字""具体原因不明,如果要对某一类对象进行操作,看如下代码
#include "testqt.h"
#include <QDebug>
#include <iostream>
using namespace std;
static QObject *PrintName(QObject *obj)
{
QObjectList cs = obj->children();
if (!obj)//为NULL就退出
{
return NULL;
}
cout << obj->objectName().toStdString();//获取控件对象名字
const QMetaObject *mobj = obj->metaObject();//获取控件对象类型
cout << ":" << mobj->className() << endl;
QString cName = mobj->className();
if (cName == "QPushButton")
{
QPushButton *pb = qobject_cast<QPushButton *>(obj);
if (pb)
{
pb->setText(pb->text() + "class");
}
}
if (cs.size() <= 0)
{
return NULL;
}
for (int i = 0; i < cs.size(); i++)
{
PrintName(cs[i]);
}
}
testqt::testqt(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
QObjectList cs = this->children();//访问当前子节点控件
PrintName(this);
qDebug() << "*******************";
for (int i = 0; i < cs.size(); i++)
{
qDebug() << cs[i]->objectName();
}
//qDebug() << endl;
QObjectList gs = ui.widget->children();
for (int i = 0; i < gs.size(); i++)
{
qDebug() << gs[i]->objectName();
}
}
结果
以上就通过访问界面上控件的方式对界面上键盘类控件对按键的名字进行了修改