DEV Community

海前 王
海前 王

Posted on

meta

/*#include <QApplication>
#include <QWidget>
#include <QDebug>

#include <QWidget>

class MyDerivedWidget1 : public QWidget {
    Q_OBJECT
public:
    explicit MyDerivedWidget1(QWidget *parent = nullptr){};
};



int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    // Create an instance of MyDerivedWidget1
    MyDerivedWidget1 *widget1 = new MyDerivedWidget1();
    if (widget1) {
        widget1->show();
        qDebug() << "Created widget of type:" << widget1->metaObject()->className();
    } else {
        qDebug() << "Failed to create MyDerivedWidget1";
    }
    widget1->metaObject()->className();

    return app.exec();
}
#include"main.moc"
*/

#include <QApplication>
#include <QWidget>
#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QVBoxLayout>
#include <QMetaObject>
#include <QMetaMethod>
#include <QDebug>

// 假设这是自定义的控件类
class MyDerivedWidget1 : public QWidget {
    Q_OBJECT
public:
    explicit MyDerivedWidget1(QWidget *parent = nullptr) : QWidget(parent) {
        QVBoxLayout *layout = new QVBoxLayout(this);
        QPushButton *button = new QPushButton("Click Me", this);
        layout->addWidget(button);

        // 使用 QObject::connect 方法连接信号和槽
        connect(button, &QPushButton::clicked, this, &MyDerivedWidget1::onButtonClicked);
    }

public slots:
    void onButtonClicked() {
        qDebug() << "Button clicked!";
    }
};

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    // 动态创建控件
    MyDerivedWidget1 *widget = new MyDerivedWidget1();
    widget->show();

    // 获取信号和槽
    const QMetaObject *metaObject = widget->metaObject();
    int signalIndex = metaObject->indexOfSignal(QMetaObject::normalizedSignature("clicked()"));
    int slotIndex = metaObject->indexOfSlot(QMetaObject::normalizedSignature("onButtonClicked()"));

    if (signalIndex != -1 && slotIndex != -1) {
        QMetaMethod signalMethod = metaObject->method(signalIndex);
        QMetaMethod slotMethod = metaObject->method(slotIndex);



        // 动态连接信号和槽
        QObject::connect(widget->findChild<QPushButton*>(), signalMethod, widget, slotMethod);
    } else {
        qDebug() << "Failed to find signal or slot";
    }

    return app.exec();
}

#include"main.moc"

Enter fullscreen mode Exit fullscreen mode

Top comments (0)