/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtWidgets>#include "mainwindow.h"#include "mdichild.h"
MainWindow::MainWindow()
: mdiArea(newQMdiArea)
{
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()
{
MdiChild *child = createMdiChild();
child->newFile();
child->show();
}
void MainWindow::open()
{
constQString fileName =QFileDialog::getOpenFileName(this);
if (!fileName.isEmpty())
openFile(fileName);
}
bool MainWindow::openFile(constQString&fileName)
{
if (QMdiSubWindow*existing = findMdiChild(fileName)) {
mdiArea->setActiveSubWindow(existing);
returntrue;
}
const bool succeeded = loadFile(fileName);
if (succeeded)
statusBar()->showMessage(tr("File loaded"),2000);
return succeeded;
}
bool MainWindow::loadFile(constQString&fileName)
{
MdiChild *child = createMdiChild();
const bool succeeded = child->loadFile(fileName);
if (succeeded)
child->show();
else
child->close();
MainWindow::prependToRecentFiles(fileName);
return succeeded;
}
staticinlineQString recentFilesKey() { returnQStringLiteral("recentFileList"); }
staticinlineQString fileKey() { returnQStringLiteral("file"); }
staticQStringList readRecentFiles(QSettings&settings)
{
QStringList result;
constint count = settings.beginReadArray(recentFilesKey());
for (int i =0; i < count; ++i) {
settings.setArrayIndex(i);
result.append(settings.value(fileKey()).toString());
}
settings.endArray();
return result;
}
staticvoid writeRecentFiles(constQStringList&files,QSettings&settings)
{
constint 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());
constint count = settings.beginReadArray(recentFilesKey());
settings.endArray();
return count >0;
}
void MainWindow::prependToRecentFiles(constQString&fileName)
{
QSettings settings(QCoreApplication::organizationName(),QCoreApplication::applicationName());
constQStringList oldRecentFiles = readRecentFiles(settings);
QStringList recentFiles = oldRecentFiles;
recentFiles.removeAll(fileName);
recentFiles.prepend(fileName);
if (oldRecentFiles != recentFiles)
writeRecentFiles(recentFiles, settings);
setRecentFilesVisible(!recentFiles.isEmpty());
}
void MainWindow::setRecentFilesVisible(bool visible)
{
recentFileSubMenuAct->setVisible(visible);
recentFileSeparator->setVisible(visible);
}
void MainWindow::updateRecentFileActions()
{
QSettings settings(QCoreApplication::organizationName(),QCoreApplication::applicationName());
constQStringList recentFiles = readRecentFiles(settings);
constint count =qMin(int(MaxRecentFiles), recentFiles.size());
int i =0;
for ( ; i < count; ++i) {
constQString 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 (constQAction*action = qobject_cast<constQAction*>(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());
}
}
#ifndef QT_NO_CLIPBOARDvoid MainWindow::cut()
{
if (activeMdiChild())
activeMdiChild()->cut();
}
void MainWindow::copy()
{
if (activeMdiChild())
activeMdiChild()->copy();
}
void MainWindow::paste()
{
if (activeMdiChild())
activeMdiChild()->paste();
}
#endifvoid 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() !=0);
saveAct->setEnabled(hasMdiChild);
saveAsAct->setEnabled(hasMdiChild);
#ifndef QT_NO_CLIPBOARD
pasteAct->setEnabled(hasMdiChild);
#endif
closeAct->setEnabled(hasMdiChild);
closeAllAct->setEnabled(hasMdiChild);
tileAct->setEnabled(hasMdiChild);
cascadeAct->setEnabled(hasMdiChild);
nextAct->setEnabled(hasMdiChild);
previousAct->setEnabled(hasMdiChild);
windowMenuSeparatorAct->setVisible(hasMdiChild);
#ifndef QT_NO_CLIPBOARD
bool hasSelection = (activeMdiChild() &&
activeMdiChild()->textCursor().hasSelection());
cutAct->setEnabled(hasSelection);
copyAct->setEnabled(hasSelection);
#endif
}
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());
}
}
MdiChild *MainWindow::createMdiChild()
{
MdiChild *child =new MdiChild;
mdiArea->addSubWindow(child);
#ifndef QT_NO_CLIPBOARD
connect(child,&QTextEdit::copyAvailable, cutAct,&QAction::setEnabled);
connect(child,&QTextEdit::copyAvailable, copyAct,&QAction::setEnabled);
#endifreturn child;
}
void MainWindow::createActions()
{
QMenu*fileMenu = menuBar()->addMenu(tr("&File"));
QToolBar*fileToolBar = addToolBar(tr("File"));
constQIcon newIcon =QIcon::fromTheme("document-new",QIcon(":/images/new.png"));
newAct =newQAction(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);
constQIcon openIcon =QIcon::fromTheme("document-open",QIcon(":/images/open.png"));
QAction*openAct =newQAction(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);
constQIcon saveIcon =QIcon::fromTheme("document-save",QIcon(":/images/save.png"));
saveAct =newQAction(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);
constQIcon saveAsIcon =QIcon::fromTheme("document-save-as");
saveAsAct =newQAction(saveAsIcon, tr("Save &As..."),this);
saveAsAct->setShortcuts(QKeySequence::SaveAs);
saveAsAct->setStatusTip(tr("Save the document under a new name"));
connect(saveAsAct,&QAction::triggered,this,&MainWindow::saveAs);
fileMenu->addAction(saveAsAct);
fileMenu->addSeparator();
QMenu*recentMenu = fileMenu->addMenu(tr("Recent..."));
connect(recentMenu,&QMenu::aboutToShow,this,&MainWindow::updateRecentFileActions);
recentFileSubMenuAct = recentMenu->menuAction();
for (int i =0; i < MaxRecentFiles; ++i) {
recentFileActs[i]= recentMenu->addAction(QString(),this,&MainWindow::openRecentFile);
recentFileActs[i]->setVisible(false);
}
recentFileSeparator = fileMenu->addSeparator();
setRecentFilesVisible(MainWindow::hasRecentFiles());
fileMenu->addAction(tr("Switch layout direction"),this,&MainWindow::switchLayoutDirection);
fileMenu->addSeparator();
constQIcon 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);
#ifndef QT_NO_CLIPBOARDQMenu*editMenu = menuBar()->addMenu(tr("&Edit"));
QToolBar*editToolBar = addToolBar(tr("Edit"));
constQIcon cutIcon =QIcon::fromTheme("edit-cut",QIcon(":/images/cut.png"));
cutAct =newQAction(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);
constQIcon copyIcon =QIcon::fromTheme("edit-copy",QIcon(":/images/copy.png"));
copyAct =newQAction(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);
constQIcon pasteIcon =QIcon::fromTheme("edit-paste",QIcon(":/images/paste.png"));
pasteAct =newQAction(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);
#endif
windowMenu = menuBar()->addMenu(tr("&Window"));
connect(windowMenu,&QMenu::aboutToShow,this,&MainWindow::updateWindowMenu);
closeAct =newQAction(tr("Cl&ose"),this);
closeAct->setStatusTip(tr("Close the active window"));
connect(closeAct,&QAction::triggered,
mdiArea,&QMdiArea::closeActiveSubWindow);
closeAllAct =newQAction(tr("Close &All"),this);
closeAllAct->setStatusTip(tr("Close all the windows"));
connect(closeAllAct,&QAction::triggered, mdiArea,&QMdiArea::closeAllSubWindows);
tileAct =newQAction(tr("&Tile"),this);
tileAct->setStatusTip(tr("Tile the windows"));
connect(tileAct,&QAction::triggered, mdiArea,&QMdiArea::tileSubWindows);
cascadeAct =newQAction(tr("&Cascade"),this);
cascadeAct->setStatusTip(tr("Cascade the windows"));
connect(cascadeAct,&QAction::triggered, mdiArea,&QMdiArea::cascadeSubWindows);
nextAct =newQAction(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 =newQAction(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 =newQAction(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());
constQByteArray geometry = settings.value("geometry",QByteArray()).toByteArray();
if (geometry.isEmpty()) {
constQRect availableGeometry =QApplication::desktop()->availableGeometry(this);
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());
return0;
}
QMdiSubWindow*MainWindow::findMdiChild(constQString&fileName) const
{
QString canonicalFilePath =QFileInfo(fileName).canonicalFilePath();
foreach (QMdiSubWindow*window, mdiArea->subWindowList()) {
MdiChild *mdiChild = qobject_cast<MdiChild *>(window->widget());
if (mdiChild->currentFile() == canonicalFilePath)
return window;
}
return0;
}
void MainWindow::switchLayoutDirection()
{
if (layoutDirection() ==Qt::LeftToRight)
QGuiApplication::setLayoutDirection(Qt::RightToLeft);
elseQGuiApplication::setLayoutDirection(Qt::LeftToRight);
}