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

Qt中如何将QFile对象从一个按钮点击事件传递到另一个?

Hey there! The issue here is that your input_file is a local variable inside on_pushButton_clicked() — once that function finishes running, the variable gets destroyed, so on_pushButton_2_clicked() can't access it at all.

To fix this, you need to make input_file a member variable of your MainWindow class. Here's how to do it step by step:

Step 1: Update your MainWindow header file (.h)

Add a QFile declaration to the private section of your class so it's accessible across all member functions:

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_pushButton_clicked();
    void on_pushButton_2_clicked();

private:
    Ui::MainWindow *ui;
    QFile input_file; // Add this line as a member variable
};

Step 2: Modify on_pushButton_clicked()

Instead of creating a local QFile, use the member variable. Also, note that setText() can't take a QFile directly — you need to read the content first with a QTextStream:

void MainWindow::on_pushButton_clicked() { 
    QString filepath = QFileDialog::getOpenFileName( 
        this, 
        "Open Document", 
        QDir::currentPath(), 
        "All files (*.*) ;; Document files (*.doc *.rtf);; PNG files (*.png)"
    ); 

    // First, close the file if it was already open
    if (input_file.isOpen()) {
        input_file.close();
    }

    input_file.setFileName(filepath);
    if(!input_file.open(QIODevice::ReadOnly)) {
        QMessageBox::information(this,"Info",input_file.errorString());
        return;
    }

    // Read the file content and display it in textBrowser
    QTextStream in(&input_file);
    QString content = in.readAll();
    ui->textBrowser->setText(content);
}

Step 3: Update on_pushButton_2_clicked()

Now you can safely use the member input_file here. Just make sure to check if it's open first:

void MainWindow::on_pushButton_2_clicked() { 
    if (!input_file.isOpen()) {
        QMessageBox::warning(this, "Warning", "No file is open!");
        return;
    }

    // Reset the stream to the start of the file if needed
    input_file.seek(0);
    QTextStream input_text_stream(&input_file);

    // Now you can work with input_text_stream, e.g.:
    // QString line = input_text_stream.readLine();
}

Important Notes:

  • Always check if the file is open before operating on it to avoid runtime errors.
  • When you're done with the file (e.g., when closing the window), make sure to close it in the destructor or relevant cleanup function.
  • For binary files, you'd use QDataStream instead of QTextStream, but since you're displaying content in a textBrowser, QTextStream is the right choice here.

内容的提问来源于stack exchange,提问作者superstack

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:01:38