Qt中 QWidget 和 QMainWindow 区别
QWidget 用来构建简单窗口
QMainWindow 用来构建更复杂的窗口,QMainWindow 继承自QWidget,在QWidget 的基础上提供了菜单栏、工具栏、状态栏等功能
- 菜单栏(
QMenuBar
) - 工具栏(
QToolBar
) - 状态栏(
QStatusBar
) - 中央窗口区域(
setCentralWidget()
)
#include <QAction>
#include <QApplication>
#include <QMainWindow>
#include <QMenuBar>
#include <QMessageBox>
class MyWindow : public QMainWindow {
public:
MyWindow()
{
// 创建菜单栏
QMenuBar* menuBar = this->menuBar();
// 创建菜单
QMenu* fileMenu = menuBar->addMenu("File");
// 创建菜单项
QAction* newAction = new QAction("New", this);
QAction* openAction = new QAction("Open", this);
QAction* exitAction = new QAction("Exit", this);
// 将菜单项添加到菜单中
fileMenu->addAction(newAction);
fileMenu->addAction(openAction);
fileMenu->addSeparator(); // 添加分隔符
fileMenu->addAction(exitAction);
// 连接信号和槽
connect(newAction, &QAction::triggered, this, &MyWindow::newFile);
connect(openAction, &QAction::triggered, this, &MyWindow::openFile);
connect(exitAction, &QAction::triggered, this, &MyWindow::exitApp);
}
private:
void newFile()
{
QMessageBox::information(this, "New File", "New file action triggered!");
}
void openFile()
{
QMessageBox::information(this, "Open File", "Open file action triggered!");
}
void exitApp()
{
QApplication::quit();
}
};
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
MyWindow window;
window.resize(800, 600);
window.show();
return app.exec();
}