QMetaMethod Class
La clase QMetaMethod proporciona metadatos sobre una función miembro. Más...
| Cabecera: | #include <QMetaMethod> |
| CMake: | find_package(Qt6 REQUIRED COMPONENTS Core)target_link_libraries(mytarget PRIVATE Qt6::Core) |
| qmake: | QT += core |
Esta clase es igual-comparable.
Tipos Públicos
| enum | Access { Private, Protected, Public } |
| enum | MethodType { Method, Signal, Slot, Constructor } |
Funciones Públicas
| QMetaMethod::Access | access() const |
(since 6.5) bool | invoke(QObject *obj, Args &&... arguments) const |
(since 6.5) bool | invoke(QObject *obj, QTemplatedMetaMethodReturnArgument<ReturnArg> ret, Args &&... arguments) const |
(since 6.5) bool | invoke(QObject *obj, Qt::ConnectionType type, Args &&... arguments) const |
(since 6.5) bool | invoke(QObject *obj, Qt::ConnectionType type, QTemplatedMetaMethodReturnArgument<ReturnArg> ret, Args &&... arguments) const |
(since 6.5) bool | invokeOnGadget(void *gadget, Args &&... arguments) const |
(since 6.5) bool | invokeOnGadget(void *gadget, QTemplatedMetaMethodReturnArgument<ReturnArg> ret, Args &&... arguments) const |
(since 6.2) bool | isConst() const |
| bool | isValid() const |
| int | methodIndex() const |
| QByteArray | methodSignature() const |
| QMetaMethod::MethodType | methodType() const |
| QByteArray | name() const |
(since 6.9) QByteArrayView | nameView() const |
| int | parameterCount() const |
(since 6.0) QMetaType | parameterMetaType(int index) const |
| QList<QByteArray> | parameterNames() const |
| int | parameterType(int index) const |
(since 6.0) QByteArray | parameterTypeName(int index) const |
| QList<QByteArray> | parameterTypes() const |
(since 6.0) int | relativeMethodIndex() const |
(since 6.0) QMetaType | returnMetaType() const |
| int | returnType() const |
| int | revision() const |
| const char * | tag() const |
| const char * | typeName() const |
Miembros públicos estáticos
| QMetaMethod | fromSignal(PointerToMemberFunction signal) |
No miembros relacionados
| bool | operator!=(const QMetaMethod &lhs, const QMetaMethod &rhs) |
| bool | operator==(const QMetaMethod &lhs, const QMetaMethod &rhs) |
Macros
Descripción Detallada
Un QMetaMethod tiene un especificador methodType(), un especificador methodSignature(), una lista de parameterTypes() y parameterNames(), un especificador return typeName(), un especificador tag(), y un especificador access(). Puede utilizar invoke() para invocar el método en un QObject arbitrario.
Véase también QMetaObject, QMetaEnum, QMetaProperty, y Sistema de propiedades de Qt.
Documentación de tipos de miembros
enum QMetaMethod::Access
Este enum describe el nivel de acceso de un método, siguiendo las convenciones utilizadas en C++.
| Constante | Valor |
|---|---|
QMetaMethod::Private | 0 |
QMetaMethod::Protected | 1 |
QMetaMethod::Public | 2 |
enum QMetaMethod::MethodType
| Constante | Valor | Descripción |
|---|---|---|
QMetaMethod::Method | QMETHOD_CODE | La función es una función miembro simple. |
QMetaMethod::Signal | 1 | La función es una señal. |
QMetaMethod::Slot | 2 | La función es una ranura. |
QMetaMethod::Constructor | 3 | La función es un constructor. |
Documentación de la función miembro
QMetaMethod::Access QMetaMethod::access() const
Devuelve la especificación de acceso de este método (privado, protegido o público).
Nota: Las señales son siempre públicas, pero debe considerar esto como un detalle de implementación. Casi siempre es una mala idea emitir una señal desde fuera de su clase.
Véase también methodType().
[static] template <typename PointerToMemberFunction> QMetaMethod QMetaMethod::fromSignal(PointerToMemberFunction signal)
Devuelve el metamétodo que corresponde al signal dado, o un QMetaMethod inválido si signal es nullptr o no es una señal de la clase.
Ejemplo:
QMetaMethod destroyedSignal = QMetaMethod::fromSignal(&QObject::destroyed);
[since 6.5] template <typename ReturnArg, typename... Args> bool QMetaMethod::invoke(QObject *obj, Qt::ConnectionType type, QTemplatedMetaMethodReturnArgument<ReturnArg> ret, Args &&... arguments) const
[since 6.5] template <typename... Args> bool QMetaMethod::invoke(QObject *obj, Qt::ConnectionType type, Args &&... arguments) const
[since 6.5] template <typename ReturnArg, typename... Args> bool QMetaMethod::invoke(QObject *obj, QTemplatedMetaMethodReturnArgument<ReturnArg> ret, Args &&... arguments) const
[since 6.5] template <typename... Args> bool QMetaMethod::invoke(QObject *obj, Args &&... arguments) const
Invoca este método en el objeto object. Devuelve true si el miembro pudo ser invocado. Devuelve false si no existe tal miembro o los parámetros no coinciden.
Para las sobrecargas con un parámetro QTemplatedMetaMethodReturnArgument, el valor de retorno de la llamada a la función member se coloca en ret. Para las sobrecargas sin dicho miembro, se descartará el valor de retorno de la función llamada (si existe). QTemplatedMetaMethodReturnArgument es un tipo interno que no debe utilizarse directamente. En su lugar, utilice la función qReturnArg().
Las sobrecargas con un parámetro Qt::ConnectionType type permiten seleccionar explícitamente si la invocación será síncrona o no:
- Si type es Qt::DirectConnection, el miembro se invocará inmediatamente en el subproceso actual.
- Si type es Qt::QueuedConnection, se enviará un QEvent y el miembro se invocará en cuanto la aplicación entre en el bucle de eventos en el hilo en el que se creó o al que se movió el obj.
- Si type es Qt::BlockingQueuedConnection, el método se invocará de la misma manera que para Qt::QueuedConnection, excepto que el hilo actual se bloqueará hasta que se envíe el evento. El uso de este tipo de conexión para comunicarse entre objetos en el mismo hilo provocará bloqueos.
- Si type es Qt::AutoConnection, el miembro se invoca de forma sincrónica si obj vive en el mismo hilo que el invocador; en caso contrario, invocará al miembro de forma asincrónica. Este es el comportamiento de las sobrecargas que no tienen el parámetro type.
Para invocar asíncronamente la ranura animateClick() en un QPushButton:
int methodIndex = pushButton->metaObject()->indexOfMethod("animateClick()"); QMetaMethod method = metaObject->method(methodIndex); method.invoke(pushButton, Qt::QueuedConnection);
Con invocaciones asíncronas de métodos, los parámetros deben ser tipos copiables, porque Qt necesita copiar los argumentos para almacenarlos en un evento entre bastidores. Desde Qt 6.5, esta función registra automáticamente los tipos que se están usando; sin embargo, como efecto secundario, no es posible hacer llamadas usando tipos que sólo están declarados hacia adelante. Además, tampoco es posible realizar llamadas asíncronas que utilicen como parámetros referencias a tipos no calificados como const.
Para invocar sincrónicamente la ranura compute(QString, int, double) en algún objeto arbitrario obj recuperar su valor de retorno:
QString retVal; QByteArray normalizedSignature = QMetaObject::normalizedSignature("compute(QString, int, double)"); int methodIndex = obj->metaObject()->indexOfMethod(normalizedSignature); QMetaMethod method = obj->metaObject()->method(methodIndex); method.invoke(obj, Qt::DirectConnection, qReturnArg(retVal), QString("sqrt"), 42, 9.7);
Si la ranura "compute" no toma exactamente un QString, un int, y un double en el orden especificado, la llamada fallará. Nótese cómo fue necesario ser explícito sobre el tipo de QString, ya que el literal de carácter no es exactamente el tipo correcto para coincidir. Si el método en su lugar tomara un QByteArray, un qint64, y un long double, la llamada necesitaría ser escrita como:
QString retVal; QByteArray normalizedSignature = QMetaObject::normalizedSignature("compute(QByteArray, qint64, long double)"); int methodIndex = obj->metaObject()->indexOfMethod(normalizedSignature); QMetaMethod method = obj->metaObject()->method(methodIndex); method.invoke(obj, Qt::DirectConnection, qReturnArg(retVal), QByteArray("sqrt"), qint64(42), 9.7L);
La misma llamada puede ejecutarse utilizando las macros Q_ARG() y Q_RETURN_ARG() , como en:
QString retVal; QByteArray normalizedSignature = QMetaObject::normalizedSignature("compute(QString, int, double)"); int methodIndex = obj->metaObject()->indexOfMethod(normalizedSignature); QMetaMethod method = obj->metaObject()->method(methodIndex); method.invoke(obj, Qt::DirectConnection, Q_RETURN_ARG(QString, retVal), Q_ARG(QString, "sqrt"), Q_ARG(int, 42), Q_ARG(double, 9.7));
Advertencia: este método no comprobará la validez de los argumentos: object debe ser una instancia de la clase del QMetaObject con la que se ha construido este QMetaMethod.
Estas funciones se introdujeron en Qt 6.5.
Véase también Q_ARG(), Q_RETURN_ARG(), qRegisterMetaType(), y QMetaObject::invokeMethod().
[since 6.5] template <typename ReturnArg, typename... Args> bool QMetaMethod::invokeOnGadget(void *gadget, QTemplatedMetaMethodReturnArgument<ReturnArg> ret, Args &&... arguments) const
[since 6.5] template <typename... Args> bool QMetaMethod::invokeOnGadget(void *gadget, Args &&... arguments) const
Invoca este método en un Q_GADGET. Devuelve true si el miembro pudo ser invocado. Devuelve false si no existe tal miembro o los parámetros no coinciden.
El puntero gadget debe apuntar a una instancia de la clase gadget.
La invocación es siempre sincrónica.
Para la sobrecarga con un parámetro QTemplatedMetaMethodReturnArgument, el valor de retorno de la llamada a la función member se coloca en ret. Para la sobrecarga sin él, el valor de retorno de la función llamada (si existe) se descartará. QTemplatedMetaMethodReturnArgument es un tipo interno que no debe utilizar directamente. En su lugar, utilice la función qReturnArg().
Advertencia: este método no comprobará la validez de los argumentos: gadget debe ser una instancia de la clase QMetaObject con la que se ha construido este QMetaMethod.
Estas funciones se introdujeron en Qt 6.5.
Véase también Q_ARG(), Q_RETURN_ARG(), qRegisterMetaType(), y QMetaObject::invokeMethod().
[since 6.2] bool QMetaMethod::isConst() const
Devuelve si el método está calificado como const.
Nota: Este método puede devolver erróneamente false para un método const si pertenece a una biblioteca compilada con una versión anterior de Qt.
Esta función se introdujo en Qt 6.2.
bool QMetaMethod::isValid() const
Devuelve true si este método es válido (puede ser introspeccionado e invocado), en caso contrario devuelve false.
int QMetaMethod::methodIndex() const
Devuelve el índice de este método.
QByteArray QMetaMethod::methodSignature() const
Devuelve la firma de este método (por ejemplo, setValue(double)).
Véase también parameterTypes() y parameterNames().
QMetaMethod::MethodType QMetaMethod::methodType() const
Devuelve el tipo de este método (señal, ranura o método).
Véase también access().
QByteArray QMetaMethod::name() const
Devuelve el nombre de este método.
Véase también methodSignature() y parameterCount().
[since 6.9] QByteArrayView QMetaMethod::nameView() const
Devuelve el nombre de este método. El QByteArrayView devuelto es válido siempre y cuando el meta-objeto de la clase a la que pertenece el método sea válido.
Esta función se introdujo en Qt 6.9.
Véase también name.
int QMetaMethod::parameterCount() const
Devuelve el número de parámetros de este método.
Véase también parameterType() y parameterNames().
[since 6.0] QMetaType QMetaMethod::parameterMetaType(int index) const
Devuelve el metatipo del parámetro en el index dado.
Si index es menor que cero o mayor que parameterCount(), se devuelve un QMetaType inválido.
Esta función se introdujo en Qt 6.0.
Véase también parameterCount(), returnMetaType(), y QMetaType.
QList<QByteArray> QMetaMethod::parameterNames() const
Devuelve una lista de nombres de parámetros.
Véase también parameterTypes() y methodSignature().
int QMetaMethod::parameterType(int index) const
Devuelve el tipo del parámetro en el index dado .
El valor devuelto es uno de los tipos registrados en QMetaType, o QMetaType::UnknownType si el tipo no está registrado.
Véase también parameterCount(), parameterMetaType(), returnType(), y QMetaType.
[since 6.0] QByteArray QMetaMethod::parameterTypeName(int index) const
Devuelve el nombre del tipo en la posición index Si no hay ningún parámetro en index, devuelve un vacío QByteArray
Esta función se introdujo en Qt 6.0.
Véase también parameterNames().
QList<QByteArray> QMetaMethod::parameterTypes() const
Devuelve una lista de tipos de parámetros.
Véase también parameterNames() y methodSignature().
[since 6.0] int QMetaMethod::relativeMethodIndex() const
Devuelve el índice local de este método dentro.
Esta función se introdujo en Qt 6.0.
[since 6.0] QMetaType QMetaMethod::returnMetaType() const
Devuelve el tipo de retorno de este método.
Esta función se introdujo en Qt 6.0.
Véase también parameterMetaType(), QMetaType, y typeName().
int QMetaMethod::returnType() const
Devuelve el tipo de retorno de este método.
El valor de retorno es uno de los tipos registrados con QMetaType, o QMetaType::UnknownType si el tipo no está registrado.
Véase también parameterType(), QMetaType, typeName(), y returnMetaType().
int QMetaMethod::revision() const
Devuelve la revisión del método si se especificó una en Q_REVISION, de lo contrario devuelve 0. Desde Qt 6.0, los valores distintos de cero se codifican y pueden descodificarse usando QTypeRevision::fromEncodedVersion().
const char *QMetaMethod::tag() const
Devuelve la etiqueta asociada a este método.
Las etiquetas son macros especiales reconocidas por moc que permiten añadir información adicional sobre un método.
La información de la etiqueta puede añadirse de la siguiente manera en la declaración de la función:
// In the class MainWindow declaration #ifndef Q_MOC_RUN // define the tag text as empty, so the compiler doesn't see it # define MY_CUSTOM_TAG #endif //... private slots: MY_CUSTOM_TAG void testFunc();
y se puede acceder a la información mediante
MainWindow win; win.show(); int functionIndex = win.metaObject()->indexOfSlot("testFunc()"); QMetaMethod mm = win.metaObject()->method(functionIndex); qDebug() << mm.tag(); // prints MY_CUSTOM_TAG
Por el momento, moc extraerá y registrará todas las etiquetas, pero no tratará ninguna de ellas de forma especial. Puedes utilizar las etiquetas para anotar tus métodos de forma diferente, y tratarlos según las necesidades específicas de tu aplicación.
Nota: moc expande las macros del preprocesador, por lo que es necesario rodear la definición con #ifndef Q_MOC_RUN , como se muestra en el ejemplo anterior.
const char *QMetaMethod::typeName() const
Devuelve el nombre del tipo de retorno de este método. Si este método es un constructor, esta función devuelve una cadena vacía (los constructores no tienen tipos de retorno).
Nota: En Qt 7, esta función devolverá un puntero nulo para los constructores.
Véase también returnType() y QMetaType::name().
No miembros relacionados
[noexcept] bool operator!=(const QMetaMethod &lhs, const QMetaMethod &rhs)
Devuelve true si el método lhs no es igual al método rhs, en caso contrario devuelve false.
[noexcept] bool operator==(const QMetaMethod &lhs, const QMetaMethod &rhs)
Devuelve true si el método lhs es igual al método rhs, en caso contrario devuelve false.
Documentación de macros
Q_METAMETHOD_INVOKE_MAX_ARGS
Equivale al número máximo de argumentos disponibles para la ejecución del método a través de QMetaMethod::invoke()
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.