如何仅查找小部件(例如 QPushButton)Qt Designer 在属性编辑器中显示的那些属性? 我可以使用以下代码找到所有属性,包括 Qt Designer 中未显示的属性:
// Print all available properties of a Widget:
qDebug()<<qPrintable("Widget: QPushButton");
QObject *object = new QPushButton;
const QMetaObject *metaobject = object->metaObject();
for (int i=0; i<metaobject->propertyCount(); ++i) {
QMetaProperty metaproperty = metaobject->property(i);
const char *name = metaproperty.name();
QVariant value = object->property(name);
qDebug()<<qPrintable("\n" + QString(name) + "\n" + QString(value.typeName()));
}
最佳答案
isDesignable()应该告诉该属性是否会显示在 Qt Designer 中。
如 Qt Documentation 中所述:
The DESIGNABLE attribute indicates whether the property should be visible in the property editor of GUI design tool (e.g., Qt Designer). Most properties are DESIGNABLE (default true). Instead of true or false, you can specify a boolean member function.
此外,设计器中似乎未显示只读属性。
按照您的示例:
// Print all available properties of a Widget:
qDebug()<<qPrintable("Widget: QPushButton");
QPushButton *object = new QPushButton(this);
const QMetaObject *metaobject = object->metaObject();
for (int i=0; i<metaobject->propertyCount(); ++i) {
QMetaProperty metaproperty = metaobject->property(i);
const char *name = metaproperty.name();
QVariant value = object->property(name);
bool isReadOnly = metaproperty.isReadable() && !metaproperty.isWritable();
bool isWinModal = metaproperty.name() == QString("windowModality"); // removed windowModality manually
if(!isReadOnly && metaproperty.isDesignable(object) && !isWinModal){
qDebug() << metaproperty.name();
}
}
打印:
Widget: QPushButton
objectName
enabled
geometry
sizePolicy
minimumSize
maximumSize
sizeIncrement
baseSize
palette
font
cursor
mouseTracking
tabletTracking
focusPolicy
contextMenuPolicy
acceptDrops
toolTip
toolTipDuration
statusTip
whatsThis
accessibleName
accessibleDescription
layoutDirection
autoFillBackground
styleSheet
locale
inputMethodHints
text
icon
iconSize
shortcut
checkable
autoRepeat
autoExclusive
autoRepeatDelay
autoRepeatInterval
autoDefault
default
flat
但是对此有一些注意事项:
- Designer 上的属性可见性可以通过其他属性设置打开和关闭。例如,仅当 bool 属性
setCheckable
设置为 true 时,checked
属性才可设计。
摘自 QAbstractButton 定义:
Q_PROPERTY(bool checkable READ isCheckable WRITE setCheckable)
Q_PROPERTY(bool checked READ isChecked WRITE setChecked DESIGNABLE isCheckable NOTIFY toggled USER true)
- 因此,为了实现您想要的效果,我排除了只读和
windowModality
属性,但这有点hacky。我不确定是否有更好的方法来做到这一点。
关于qt - 如何仅查找 Qt Designer 中显示的小部件的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55355246/