class MyWord : public QMainWindow{.....}
void MyWord::fileOpen()
{
QString fileName = QFileDialog::getOpenFileName(this, QStringLiteral("打开"),QString(), QStringLiteral("HTML 文档 (*.htm *.html);;所有文件 (*.*)"));
if (!fileName.isEmpty()) {
QMdiSubWindow *existing = findMyChild(fileName);
if (existing) { // 若文档已打开,则直接激活
mdiArea->setActiveSubWindow(existing);
return;
}
MyChild *child = createMyChild();
if (child->loadFile(fileName)) {
statusBar()->showMessage(QStringLiteral("文件已载入"), 2000);
child->show();
enabledText(); //使得字体设置菜单可用
} else {
child->close();
}
}
}
QMdiSubWindow *MyWord::findMyChild(const QString &fileName)
{
QString canonicalFilePath = QFileInfo(fileName).canonicalFilePath();
foreach (QMdiSubWindow *window, mdiArea->subWindowList()) {
MyChild *myChild = qobject_cast<MyChild *>(window->widget());
if (myChild->currentFile() == canonicalFilePath)
return window;
}
return 0;
}
QFileInfo类的canonicalFilePath()方法,可以除去路径中的符号链接,如“.”,“..”等符号。
class MyChild : public QTextEdit{.....}
bool MyChild::loadFile(const QString &fileName)
{
if (!fileName.isEmpty()) {
if (!QFile::exists(fileName))
return false;
QFile file(fileName);
if (!file.open(QFile::ReadOnly))
return false;
QByteArray data = file.readAll();
QTextCodec *codec = Qt::codecForHtml(data);
QString str = codec->toUnicode(data);
if (Qt::mightBeRichText(str)) {
this->setHtml(str);
} else {
str = QString::fromLocal8Bit(data);
this->setPlainText(str);
}
setCurrentFile(fileName);
connect(document(), SIGNAL(contentsChanged()),this, SLOT(documentWasModified()));
return true;
}
}