可以通过在 MainWindow
类中添加一个 “Close” 按钮来实现关闭窗口的功能。以下是修改后的代码:
#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QFileDialog>
#include <QSoundEffect>
class MainWindow : public QWidget {
public:
MainWindow(QWidget *parent = nullptr) : QWidget(parent) {
QPushButton *openButton = new QPushButton("Open File", this);
connect(openButton, &QPushButton::clicked, this, &MainWindow::openFile);
QPushButton *closeButton = new QPushButton("Close", this);
connect(closeButton, &QPushButton::clicked, this, &MainWindow::close);
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(openButton);
layout->addWidget(closeButton);
setLayout(layout);
}
private slots:
void openFile() {
QString filePath = QFileDialog::getOpenFileName(this, "Select WAV File", "", "WAV Files (*.wav)");
if (!filePath.isEmpty()) {
playAudio(filePath);
}
}
void playAudio(const QString& filePath) {
QSoundEffect *effect = new QSoundEffect;
effect->setSource(QUrl::fromLocalFile(filePath));
effect->setVolume(0.5); // 设置音量,范围为0-1
effect->play();
}
};
int main(int argc, char **argv) {
QApplication app(argc, argv);
MainWindow mainWindow;
mainWindow.show();
return app.exec();
}
这个示例中,在 MainWindow
类中添加了一个名为 “Close” 的按钮,并连接到 close()
槽函数,用于关闭窗口。同时使用了水平布局管理器 QHBoxLayout
将两个按钮放在一行显示。点击 “Close” 按钮即可关闭窗口。
内容由零声教学AI助手提供,问题来源于学员提问