You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Qt按钮点击后qDebug无输出的问题求助

Qt按钮点击后qDebug无输出的问题求助

我最近在尝试用Qt的信号槽机制实现一个小功能:点击按钮选择文件后,控制台应该输出选中的文件路径,但现在点击按钮后完全没反应。按钮是通过Qt Designer创建的,而且我测试过如果把信号在同一个文件里接收(比如在MainWindow自己的槽里处理)是能正常工作的,跨类的信号槽就出问题了。

以下是我的代码:

controller.h

#ifndef CONTROLLER_H
#define CONTROLLER_H

#include "mainwindow.h"
#include "model.h"
#include <QMainWindow>
#include <QObject>
#include <QDebug>

class Controller : public QObject
{
    Q_OBJECT
public:
    explicit Controller(QObject *parent = nullptr);
    ~Controller();

public slots:
    void onFileSelected(const QString& filePath);

private:
    // Model* model = nullptr;
    MainWindow* view = nullptr;
};

#endif // CONTROLLER_H

controller.cpp

#include "controller.h"

Controller::Controller(QObject *parent)
    : QObject(parent)
{
    // model = new Model(this);
    view = new MainWindow();
    connect(view, &MainWindow::fileSelected, this, &Controller::onFileSelected);
}

Controller::~Controller()
{
    // delete model;
    delete view;
}

void Controller::onFileSelected(const QString& filePath)
{
    qDebug() << "File selected: " << filePath;
    // qDebug() << model->getHeaders();
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

signals:
    void fileSelected(const QString& filePath);

private slots:
    void on_pushButton_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QFileDialog>
#include <QTextStream>
#include <QDebug>
#include <QMessageBox>
#include <QtCharts>

using namespace QtCharts;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    QString filePath = QFileDialog::getOpenFileName(this, "choose file", QDir::currentPath());
    emit fileSelected(filePath);
}

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.setMinimumSize(1200, 900);
    w.show();
    return a.exec();
}

有没有大佬能帮忙看看哪里出问题了?我实在找不到信号槽没触发的原因...

备注:内容来源于stack exchange,提问作者r4oot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.21 15:02:59