抱歉,可能是我之前的回答有误。在Qt中确实存在QHBoxLayout和其他布局管理器用于更好地组织窗口中的控件。下面是一个示例代码,展示如何使用QVBoxLayout进行布局:
#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QFileDialog>
#include <QSoundEffect>
#include <QVBoxLayout>
class MyWindow : public QWidget {
public:
MyWindow(QWidget *parent = nullptr) : QWidget(parent) {
QPushButton *openButton = new QPushButton("Open File", this);
connect(openButton, &QPushButton::clicked, this, &MyWindow::openFile);
QPushButton *closeButton = new QPushButton("Close", this);
connect(closeButton, &QPushButton::clicked, this, &QWidget::close);
QVBoxLayout *layout = new QVBoxLayout;
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);
MyWindow myWindow;
myWindow.show();
return app.exec();
}
这个示例代码创建了一个 MyWindow
类,其中包含一个 “Open File” 按钮和一个 “Close” 按钮。它们使用 QVBoxLayout
布局进行垂直排列,并通过 addWidget()
方法添加到布局中。这样,当窗口调整大小时,控件也会相应地重新布局。
希望这个示例能对你有所帮助!如果还有其他问题,请随时提问。
内容由零声教学AI助手提供,问题来源于学员提问