MDI Example
MDI示例演示如何使用Qt的QMdiArea类实现多文档接口。大部分的操作和 SDI Example 相似。
main.cpp
删除了基于控制台命令的处理部分
#include <QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
Q_INIT_RESOURCE(mdi);
QApplication app(argc, argv);
QCoreApplication::setApplicationName("MDI Example");
QCoreApplication::setOrganizationName("QtProject");
QCoreApplication::setApplicationVersion(QT_VERSION_STR);
MainWindow mainWin;
mainWin.show();
return app.exec();
}
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QtWidgets>
class MdiChild;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow();
bool openFile(const QString &fileName);
protected:
void closeEvent(QCloseEvent *event) override;
private slots:
void newFile();
void open();
void save();
void saveAs();
void updateRecentFileActions();
void openRecentFile();
void cut();
void copy();
void paste();
void about();
void updateMenus();
void updateWindowMenu();
MdiChild *createMdiChild();
void switchLayoutDirection();
private:
enum { MaxRecentFiles = 5 };
void createActions();
void createStatusBar();
void readSettings();
void writeSettings();
bool loadFile(const QString &fileName);
static bool hasRecentFiles();
void prependToRecentFiles(const QString &fileName);
void setRecentFilesVisible(bool visible);
MdiChild *activeMdiChild() const;
QMdiSubWindow *findMdiChild(const QString &fileName) const;
QMdiArea *mdiArea;
QMenu *windowMenu;
QAction *newAct;
QAction *saveAct;
QAction *saveAsAct;
QAction *recentFileActs[MaxRecentFiles];
QAction *recentFileSeparator;
QAction *recentFileSubMenuAct;
QAction *cutAct;
QAction *copyAct;
QAction *pasteAct;
QAction *closeAct;
QAction *closeAllAct;
QAction *tileAct;
QAction *cascadeAct;
QAction *nextAct;
QAction *previousAct;
QAction *windowMenuSeparatorAct;
};
#endif
MainWindow.cpp
#include <QtWidgets>
#include "mainwindow.h"
#include "mdichild.h"
/* 构造函数 */
MainWindow::MainWindow()
: mdiArea(new QMdiArea)
{
mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
setCentralWidget(mdiArea); // 中央控件
// 子窗口激活,那就调用更新菜单函数
connect(mdiArea, &QMdiArea::subWindowActivated,this, &MainWindow::updateMenus);
createActions(); // 创建操作,并布置到主界面
createStatusBar(); // 创建状态栏
updateMenus(); // // 更新菜单项的状态
readSettings(); // 读取配置
setWindowTitle(tr("MDI"));
setUnifiedTitleAndToolBarOnMac(true);
}
/* 关闭事件 */
void MainWindow::closeEvent(QCloseEvent *event)
{
mdiArea->closeAllSubWindows(); // 关闭所有子窗口
if (mdiArea->currentSubWindow()) { // 有当前窗口
event->ignore(); // 那就算了
} else { // 没有当前窗口
writeSettings(); // 写保存选项
event->accept(); // 事情了了
}
}
/* 新建文件*/
void MainWindow::newFile()
{
// 创建子窗口-- QTextEdit
MdiChild *child = createMdiChild();
child->newFile();
child->show();
}
/* 打开操作,获取文件名 */
void MainWindow::open()
{
const QString fileName = QFileDialog::getOpenFileName(this);
if (!fileName.isEmpty())
openFile(fileName);
}
/* 打开文件 */
bool MainWindow::openFile(const QString &fileName)
{
if (QMdiSubWindow *existing = findMdiChild(fileName)) {
mdiArea->setActiveSubWindow(existing);
return true;
}
const bool succeeded = loadFile(fileName);
if (succeeded)
statusBar()->showMessage(tr("File loaded"), 2000);
return succeeded;
}
/* 导入文件内容 */
bool MainWindow::loadFile(const QString &fileName)
{
MdiChild *child = createMdiChild(); // 创建子窗口
const bool succeeded = child->loadFile(fileName);
if (succeeded)
child->show();
else
child->close();
MainWindow::prependToRecentFiles(fileName); // 添加最近访问内容
return succeeded;
}
static inline QString recentFilesKey() { return QStringLiteral("recentFileList"); }
static inline QString fileKey() { return QStringLiteral("file"); }
// 读取配置
static QStringList readRecentFiles(QSettings &settings)
{
QStringList result;
const int count = settings.beginReadArray(recentFilesKey());
for (int i = 0; i < count; ++i) {
settings.setArrayIndex(i);
result.append(settings.value(fileKey()).toString());
}
settings.endArray();
return result;
}
// 保存配置
static void writeRecentFiles(const QStringList &files, QSettings &settings)
{
const int count = files.size();
settings.beginWriteArray(recentFilesKey());
for (int i = 0; i < count; ++i) {
settings.setArrayIndex(i);
settings.setValue(fileKey(), files.at(i));
}
settings.endArray();
}
// 是否具有最近访问的文件
bool MainWindow::hasRecentFiles()
{
QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
const int count = settings.beginReadArray(recentFilesKey());
settings.endArray();
return count > 0;
}
// 准备添加最近访问的文件
void MainWindow::prependToRecentFiles(const QString &fileName)
{
QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
const QStringList oldRecentFiles = readRecentFiles(settings);
QStringList recentFiles = oldRecentFiles;
recentFiles.removeAll(fileName);
recentFiles.prepend(fileName);
if (oldRecentFiles != recentFiles)
writeRecentFiles(recentFiles, settings);
setRecentFilesVisible(!recentFiles.isEmpty());
}
/* 是否显示RecentFiles和分隔符号 */
void MainWindow::setRecentFilesVisible(bool visible)
{
recentFileSubMenuAct->setVisible(visible);
recentFileSeparator->setVisible(visible);
}
/* 更新最近访问文件的操作 */
void MainWindow::updateRecentFileActions()
{
QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
const QStringList recentFiles = readRecentFiles(settings);
const int count = qMin(int(MaxRecentFiles), recentFiles.size());
int i = 0;
for ( ; i < count; ++i) {
const QString fileName = QFileInfo(recentFiles.at(i)).fileName();
recentFileActs[i]->setText(tr("&%1 %2").arg(i + 1).arg(fileName));
recentFileActs[i]->setData(recentFiles.at(i));
recentFileActs[i]->setVisible(true);
}
for ( ; i < MaxRecentFiles; ++i)
recentFileActs[i]->setVisible(false);
}
/* 打开最近访问的文件 */
void MainWindow::openRecentFile()
{
if (const QAction *action = qobject_cast<const QAction *>(sender()))
openFile(action->data().toString());
}
/* 保存文件 */
void MainWindow::save()
{
if (activeMdiChild() && activeMdiChild()->save())
statusBar()->showMessage(tr("File saved"), 2000);
}
/* 另存文件 */
void MainWindow::saveAs()
{
MdiChild *child = activeMdiChild();
if (child && child->saveAs()) {
statusBar()->showMessage(tr("File saved"), 2000);
MainWindow::prependToRecentFiles(child->currentFile());
}
}
void MainWindow::cut()
{
if (activeMdiChild())
activeMdiChild()->cut();
}
void MainWindow::copy()
{
if (activeMdiChild())
activeMdiChild()->copy();
}
void MainWindow::paste()
{
if (activeMdiChild())
activeMdiChild()->paste();
}
void MainWindow::about()
{
QMessageBox::about(this, tr("About MDI"),
tr("The <b>MDI</b> example demonstrates how to write multiple "
"document interface applications using Qt."));
}
// 更新菜单项的状态
void MainWindow::updateMenus()
{
// 获取到激活的子窗口
bool hasMdiChild = (activeMdiChild() != nullptr);
saveAct->setEnabled(hasMdiChild); // 启用 saveAct
saveAsAct->setEnabled(hasMdiChild); // 启用 saveAsAct
pasteAct->setEnabled(hasMdiChild); // 启用 pasteAct
closeAct->setEnabled(hasMdiChild); // 启用 closeAct
closeAllAct->setEnabled(hasMdiChild); // 启用 closeAllAct
tileAct->setEnabled(hasMdiChild); // 启用 tileAct
cascadeAct->setEnabled(hasMdiChild); // 启用 cascadeAct
nextAct->setEnabled(hasMdiChild); // 启用 nextAct
previousAct->setEnabled(hasMdiChild); // 启用 previousAct
windowMenuSeparatorAct->setVisible(hasMdiChild); // 分隔符可视
// 激活的子窗口具有选定内容
bool hasSelection = (activeMdiChild() &&
activeMdiChild()->textCursor().hasSelection());
cutAct->setEnabled(hasSelection); // 启用 cutAct
copyAct->setEnabled(hasSelection); // 启用 copyAct
}
/* 更新Window菜单 */
void MainWindow::updateWindowMenu()
{
windowMenu->clear();
windowMenu->addAction(closeAct);
windowMenu->addAction(closeAllAct);
windowMenu->addSeparator();
windowMenu->addAction(tileAct);
windowMenu->addAction(cascadeAct);
windowMenu->addSeparator();
windowMenu->addAction(nextAct);
windowMenu->addAction(previousAct);
windowMenu->addAction(windowMenuSeparatorAct);
QList<QMdiSubWindow *> windows = mdiArea->subWindowList();
windowMenuSeparatorAct->setVisible(!windows.isEmpty());
for (int i = 0; i < windows.size(); ++i) {
QMdiSubWindow *mdiSubWindow = windows.at(i);
MdiChild *child = qobject_cast<MdiChild *>(mdiSubWindow->widget());
QString text;
if (i < 9) {
text = tr("&%1 %2").arg(i + 1)
.arg(child->userFriendlyCurrentFile());
} else {
text = tr("%1 %2").arg(i + 1)
.arg(child->userFriendlyCurrentFile());
}
QAction *action = windowMenu->addAction(text, mdiSubWindow, [this, mdiSubWindow]() {
mdiArea->setActiveSubWindow(mdiSubWindow);
});
action->setCheckable(true);
action ->setChecked(child == activeMdiChild());
}
}
/* 创建子窗口并加入到MDI中,返回子窗口指针 */
MdiChild *MainWindow::createMdiChild()
{
MdiChild *child = new MdiChild;
mdiArea->addSubWindow(child);
// 子窗口的copy状态关联到cutAction和copyAct
connect(child, &QTextEdit::copyAvailable, cutAct, &QAction::setEnabled);
connect(child, &QTextEdit::copyAvailable, copyAct, &QAction::setEnabled);
return child;
}
/* 创建操作*/
void MainWindow::createActions()
{
QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
QToolBar *fileToolBar = addToolBar(tr("File"));
const QIcon newIcon = QIcon::fromTheme("document-new", QIcon(":/images/new.png"));
newAct = new QAction(newIcon, tr("&New"), this);
newAct->setShortcuts(QKeySequence::New);
newAct->setStatusTip(tr("Create a new file"));
connect(newAct, &QAction::triggered, this, &MainWindow::newFile);
fileMenu->addAction(newAct);
fileToolBar->addAction(newAct);
const QIcon openIcon = QIcon::fromTheme("document-open", QIcon(":/images/open.png"));
QAction *openAct = new QAction(openIcon, tr("&Open..."), this);
openAct->setShortcuts(QKeySequence::Open);
openAct->setStatusTip(tr("Open an existing file"));
connect(openAct, &QAction::triggered, this, &MainWindow::open);
fileMenu->addAction(openAct);
fileToolBar->addAction(openAct);
const QIcon saveIcon = QIcon::fromTheme("document-save", QIcon(":/images/save.png"));
saveAct = new QAction(saveIcon, tr("&Save"), this);
saveAct->setShortcuts(QKeySequence::Save);
saveAct->setStatusTip(tr("Save the document to disk"));
connect(saveAct, &QAction::triggered, this, &MainWindow::save);
fileToolBar->addAction(saveAct);
const QIcon saveAsIcon = QIcon::fromTheme("document-save-as");
saveAsAct = new QAction(saveAsIcon, tr("Save &As..."), this);
saveAsAct->setShortcut(tr("Ctrl+Shirt+S"));
saveAsAct->setStatusTip(tr("Save the document under a new name"));
connect(saveAsAct, &QAction::triggered, this, &MainWindow::saveAs);
fileMenu->addAction(saveAsAct);
fileMenu->addSeparator();
//增加 File | Recent...
QMenu *recentMenu = fileMenu->addMenu(tr("Recent..."));
connect(recentMenu, &QMenu::aboutToShow, this, &MainWindow::updateRecentFileActions);
recentFileSubMenuAct = recentMenu->menuAction(); // 保存菜单的操作
// 添加5个子菜单,默认空字符,不显示
for (int i = 0; i < MaxRecentFiles; ++i) {
recentFileActs[i] = recentMenu->addAction(QString(), this, &MainWindow::openRecentFile);
recentFileActs[i]->setVisible(false);
}
recentFileSeparator = fileMenu->addSeparator();
// 根据是否有recentfiles,决定是否显示相关的菜单和分隔符
setRecentFilesVisible(MainWindow::hasRecentFiles());
fileMenu->addAction(tr("Switch layout direction"), this, &MainWindow::switchLayoutDirection);
fileMenu->addSeparator();
const QIcon exitIcon = QIcon::fromTheme("application-exit");
QAction *exitAct = fileMenu->addAction(exitIcon, tr("E&xit"), qApp, &QApplication::closeAllWindows);
exitAct->setShortcuts(QKeySequence::Quit);
exitAct->setStatusTip(tr("Exit the application"));
fileMenu->addAction(exitAct);
QMenu *editMenu = menuBar()->addMenu(tr("&Edit"));
QToolBar *editToolBar = addToolBar(tr("Edit"));
const QIcon cutIcon = QIcon::fromTheme("edit-cut", QIcon(":/images/cut.png"));
cutAct = new QAction(cutIcon, tr("Cu&t"), this);
cutAct->setShortcuts(QKeySequence::Cut);
cutAct->setStatusTip(tr("Cut the current selection's contents to the "
"clipboard"));
connect(cutAct, &QAction::triggered, this, &MainWindow::cut);
editMenu->addAction(cutAct);
editToolBar->addAction(cutAct);
const QIcon copyIcon = QIcon::fromTheme("edit-copy", QIcon(":/images/copy.png"));
copyAct = new QAction(copyIcon, tr("&Copy"), this);
copyAct->setShortcuts(QKeySequence::Copy);
copyAct->setStatusTip(tr("Copy the current selection's contents to the "
"clipboard"));
connect(copyAct, &QAction::triggered, this, &MainWindow::copy);
editMenu->addAction(copyAct);
editToolBar->addAction(copyAct);
const QIcon pasteIcon = QIcon::fromTheme("edit-paste", QIcon(":/images/paste.png"));
pasteAct = new QAction(pasteIcon, tr("&Paste"), this);
pasteAct->setShortcuts(QKeySequence::Paste);
pasteAct->setStatusTip(tr("Paste the clipboard's contents into the current "
"selection"));
connect(pasteAct, &QAction::triggered, this, &MainWindow::paste);
editMenu->addAction(pasteAct);
editToolBar->addAction(pasteAct);
windowMenu = menuBar()->addMenu(tr("&Window"));
connect(windowMenu, &QMenu::aboutToShow, this, &MainWindow::updateWindowMenu);
closeAct = new QAction(tr("Cl&ose"), this);
closeAct->setStatusTip(tr("Close the active window"));
connect(closeAct, &QAction::triggered,
mdiArea, &QMdiArea::closeActiveSubWindow);
closeAllAct = new QAction(tr("Close &All"), this);
closeAllAct->setStatusTip(tr("Close all the windows"));
connect(closeAllAct, &QAction::triggered, mdiArea, &QMdiArea::closeAllSubWindows);
tileAct = new QAction(tr("&Tile"), this);
tileAct->setStatusTip(tr("Tile the windows"));
connect(tileAct, &QAction::triggered, mdiArea, &QMdiArea::tileSubWindows);
cascadeAct = new QAction(tr("&Cascade"), this);
cascadeAct->setStatusTip(tr("Cascade the windows"));
connect(cascadeAct, &QAction::triggered, mdiArea, &QMdiArea::cascadeSubWindows);
nextAct = new QAction(tr("Ne&xt"), this);
nextAct->setShortcuts(QKeySequence::NextChild);
nextAct->setStatusTip(tr("Move the focus to the next window"));
connect(nextAct, &QAction::triggered, mdiArea, &QMdiArea::activateNextSubWindow);
previousAct = new QAction(tr("Pre&vious"), this);
previousAct->setShortcuts(QKeySequence::PreviousChild);
previousAct->setStatusTip(tr("Move the focus to the previous "
"window"));
connect(previousAct, &QAction::triggered, mdiArea, &QMdiArea::activatePreviousSubWindow);
windowMenuSeparatorAct = new QAction(this);
windowMenuSeparatorAct->setSeparator(true);
updateWindowMenu();
menuBar()->addSeparator();
QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
QAction *aboutAct = helpMenu->addAction(tr("&About"), this, &MainWindow::about);
aboutAct->setStatusTip(tr("Show the application's About box"));
QAction *aboutQtAct = helpMenu->addAction(tr("About &Qt"), qApp, &QApplication::aboutQt);
aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
}
void MainWindow::createStatusBar()
{
statusBar()->showMessage(tr("Ready"));
}
void MainWindow::readSettings()
{
QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
const QByteArray geometry = settings.value("geometry", QByteArray()).toByteArray();
if (geometry.isEmpty()) {
const QRect availableGeometry = screen()->availableGeometry();
resize(availableGeometry.width() / 3, availableGeometry.height() / 2);
move((availableGeometry.width() - width()) / 2,
(availableGeometry.height() - height()) / 2);
} else {
restoreGeometry(geometry);
}
}
void MainWindow::writeSettings()
{
QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
settings.setValue("geometry", saveGeometry());
}
/* 获取激活的子窗口 */
MdiChild *MainWindow::activeMdiChild() const
{
if (QMdiSubWindow *activeSubWindow = mdiArea->activeSubWindow())
return qobject_cast<MdiChild *>(activeSubWindow->widget());
return nullptr;
}
/* 查找子窗口 */
QMdiSubWindow *MainWindow::findMdiChild(const QString &fileName) const
{
QString canonicalFilePath = QFileInfo(fileName).canonicalFilePath();
const QList<QMdiSubWindow *> subWindows = mdiArea->subWindowList();
for (QMdiSubWindow *window : subWindows) {
MdiChild *mdiChild = qobject_cast<MdiChild *>(window->widget());
if (mdiChild->currentFile() == canonicalFilePath)
return window;
}
return nullptr;
}
/* 设置布局方向 */
void MainWindow::switchLayoutDirection()
{
// void QWidget::layoutDirection()
if (layoutDirection() == Qt::LeftToRight)
QGuiApplication::setLayoutDirection(Qt::RightToLeft);
else
QGuiApplication::setLayoutDirection(Qt::LeftToRight);
}
MdiChild.h
#ifndef MDICHILD_H
#define MDICHILD_H
#include <QTextEdit>
class MdiChild : public QTextEdit
{
Q_OBJECT
public:
MdiChild();
void newFile();
bool loadFile(const QString &fileName);
bool save();
bool saveAs();
bool saveFile(const QString &fileName);
QString userFriendlyCurrentFile();
QString currentFile() { return curFile; }
protected:
void closeEvent(QCloseEvent *event) override;
private slots:
void documentWasModified();
private:
bool maybeSave();
void setCurrentFile(const QString &fileName);
QString strippedName(const QString &fullFileName);
QString curFile;
bool isUntitled;
};
#endif
MdiChild.cpp
#include <QtWidgets>
#include "mdichild.h"
MdiChild::MdiChild()
{
setAttribute(Qt::WA_DeleteOnClose);
isUntitled = true;
}
void MdiChild::newFile()
{
static int sequenceNumber = 1;
isUntitled = true;
curFile = tr("document%1.txt").arg(sequenceNumber++);
setWindowTitle(curFile + "[*]");
connect(document(), &QTextDocument::contentsChanged,
this, &MdiChild::documentWasModified);
}
bool MdiChild::loadFile(const QString &fileName)
{
QFile file(fileName);
if (!file.open(QFile::ReadOnly | QFile::Text)) {
QMessageBox::warning(this, tr("MDI"),
tr("Cannot read file %1:\n%2.")
.arg(fileName)
.arg(file.errorString()));
return false;
}
QTextStream in(&file);
QGuiApplication::setOverrideCursor(Qt::WaitCursor);
setPlainText(in.readAll());
QGuiApplication::restoreOverrideCursor();
setCurrentFile(fileName);
connect(document(), &QTextDocument::contentsChanged,
this, &MdiChild::documentWasModified);
return true;
}
bool MdiChild::save()
{
if (isUntitled) {
return saveAs();
} else {
return saveFile(curFile);
}
}
bool MdiChild::saveAs()
{
QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"),
curFile);
if (fileName.isEmpty())
return false;
return saveFile(fileName);
}
bool MdiChild::saveFile(const QString &fileName)
{
QString errorMessage;
QGuiApplication::setOverrideCursor(Qt::WaitCursor);
QSaveFile file(fileName);
if (file.open(QFile::WriteOnly | QFile::Text)) {
QTextStream out(&file);
out << toPlainText();
if (!file.commit()) {
errorMessage = tr("Cannot write file %1:\n%2.")
.arg(QDir::toNativeSeparators(fileName), file.errorString());
}
} else {
errorMessage = tr("Cannot open file %1 for writing:\n%2.")
.arg(QDir::toNativeSeparators(fileName), file.errorString());
}
QGuiApplication::restoreOverrideCursor();
if (!errorMessage.isEmpty()) {
QMessageBox::warning(this, tr("MDI"), errorMessage);
return false;
}
setCurrentFile(fileName);
return true;
}
QString MdiChild::userFriendlyCurrentFile()
{
return strippedName(curFile);
}
void MdiChild::closeEvent(QCloseEvent *event)
{
if (maybeSave()) {
event->accept();
} else {
event->ignore();
}
}
void MdiChild::documentWasModified()
{
setWindowModified(document()->isModified());
}
bool MdiChild::maybeSave()
{
if (!document()->isModified())
return true;
const QMessageBox::StandardButton ret
= QMessageBox::warning(this, tr("MDI"),
tr("'%1' has been modified.\n"
"Do you want to save your changes?")
.arg(userFriendlyCurrentFile()),
QMessageBox::Save | QMessageBox::Discard
| QMessageBox::Cancel);
switch (ret) {
case QMessageBox::Save:
return save();
case QMessageBox::Cancel:
return false;
default:
break;
}
return true;
}
void MdiChild::setCurrentFile(const QString &fileName)
{
curFile = QFileInfo(fileName).canonicalFilePath();
isUntitled = false;
document()->setModified(false);
setWindowModified(false);
setWindowTitle(userFriendlyCurrentFile() + "[*]");
}
QString MdiChild::strippedName(const QString &fullFileName)
{
return QFileInfo(fullFileName).fileName();
}