meta to object
海前 王
Posted on September 2, 2024
#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"
*/
// main.cpp
#include <QApplication>
#include <QMainWindow>
#include <QPushButton>
// main.cpp
#include <QApplication>
#include <QMainWindow>
#include <QPushButton>
#include <QMessageBox>
class MainWindow : public QMainWindow {
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
private slots:
void on_pushButton_clicked(); // 槽函数 1
void on_pushButton1_clicked(); // 槽函数 2
private:
QPushButton *pushButton;
QPushButton *pushButton1;
};
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
pushButton = new QPushButton("Click Me", this);
pushButton->setObjectName("pushButton");
pushButton->setGeometry(50, 50, 100, 30); // 设置按钮位置和大小
pushButton1 = new QPushButton("Click Me Too", this);
pushButton1->setObjectName("pushButton1");
pushButton1->setGeometry(50, 100, 100, 30); // 设置按钮位置和大小
QMetaObject::connectSlotsByName(this); // 自动连接槽
}
void MainWindow::on_pushButton_clicked() {
QMessageBox::information(this, "Button Clicked", "You clicked the first button!");
}
void MainWindow::on_pushButton1_clicked() {
QMessageBox::information(this, "Button Clicked", "You clicked the second button!");
}
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
MainWindow window;
window.show();
return app.exec();
}
#include "main.moc" // 包含自动生成的 MOC 代码
💖 💪 🙅 🚩
海前 王
Posted on September 2, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.