使用Qt开发文本编辑器(二):标签页式文档实现
Qt中相关的类
标签页俗称Tab页,Qt提供了QTableWidget用于创建基于Tab页式的文档。使用QTableWidget,我们可以很方便得添加和删除Tab、设置和获取Tab页上面的文字,设置当前的Tab。 
实现
MainWindow类中维护一个QTabWidget的指针。
新建一个文本文件时:
//新建文件
void MainWindow::newFile()
{
newNumber = (newNumber < 0 ? 0 : newNumber);
QString fileName = tr("New %1").arg(++newNumber);
openedFiles << fileName;
NotePad *notePad = new NotePad(config);
notePad->SetNewFile(true);
int index = tabWidget->addTab(notePad, fileName);
tabWidget->setCurrentIndex(index);
addToNotePadMap(index, notePad);
}
打开一个文件时:
//创建新的Tab(用于打开文件) void MainWindow::newTab(const QString& fileName, QFile& file) { int index = 0; NotePad *notePad = findNewFile(index); if(notePad == NULL) { notePad = new NotePad(config); index = tabWidget->addTab(notePad, QFileInfo(fileName).fileName()); addToNotePadMap(index, notePad); } else { notePad->SetNewFile(false); tabWidget->setTabText(index, QFileInfo(fileName).fileName()); openedFiles.removeAt(index); newNumber--; } openedFiles << fileName; QByteArray data = file.readAll(); notePad->setPlainText(QString::fromLocal8Bit(data)); tabWidget->setCurrentIndex(index); setWindowTitle(QFileInfo(fileName).fileName()); }
关闭一个文件时:
//关闭文件(指定文件) void MainWindow::fileClose(int index) { if(!shouldCloseFile()) { return; } if (maybeSave(index)) { if (openedFiles.count() == 1) { openedFiles.clear(); QString fileName = "New 1"; openedFiles << fileName; mapNotePads[0]->setPlainText(""); mapNotePads[0]->SetNewFile(true); tabWidget->setTabText(0, fileName); setWindowTitle(fileName); newNumber = 1; } else { openedFiles.removeAt(index); tabWidget->removeTab(index); removeFromNotePadMap(index); newNumber--; } } }
使用addTab来添加一个tab,setTabText设置tab页上显示的文字,removeTab移除tab,setCurrentIndex设置当前的tab。
龙心文
浙公网安备 33010602011771号