Qt跨类信号槽连接问题:主窗口按钮触发自定义类槽函数
解决方案
问题出在Custom实例被提前销毁,而非信号槽连接写法本身。你在Program构造函数里创建的Custom custom = Custom(this);是局部变量,构造函数执行完毕后该实例会被立即析构,导致信号槽连接失效,点击按钮自然无反应。
修正步骤:
给Program类添加Custom成员变量
在Program.h中,为Program类新增一个Custom类型的成员指针(推荐用智能指针避免内存泄漏):class Custom; class Program : public QMainWindow { Q_OBJECT friend class Custom; public: Program(QWidget *parent = nullptr); ~Program(); private: Ui::ProgramClass ui; Custom* m_custom; // 或者用 std::unique_ptr<Custom> m_custom; };在Program构造函数中持久化Custom实例
修改Program.cpp,将局部的Custom对象改为成员变量,确保实例在Program生命周期内始终存在:#include "Program.h" #include "Custom.h" Program::Program(QWidget *parent) : QMainWindow(parent), m_custom(nullptr) { ui.setupUi(this); // 补全括号传入this,完成UI初始化 m_custom = new Custom(this); // 若用智能指针:m_custom = std::make_unique<Custom>(this); } Program::~Program() { delete m_custom; // 用智能指针无需手动释放 }保留正确的信号槽连接写法
Custom构造函数里的连接逻辑是正确的,维持原写法即可:Custom::Custom(Program* program) : m_program(program) { QObject::connect(m_program->ui.TestButton, &QPushButton::clicked, this, &Custom::foo); }
额外注意事项:
- 必须确保
ui.setupUi(this);调用正确,否则UI控件(包括TestButton)不会被初始化,信号槽连接会直接失效。 - 若使用
std::unique_ptr,需要在Program.h中引入<memory>头文件。
修改完成后,Custom实例会与Program窗口同生命周期,点击按钮即可正常触发Custom::foo函数。
内容的提问来源于stack exchange,提问作者Powarito
相关产品推荐
相关产品推荐

