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。
源代碼的下載地址:http://download.csdn.net/detail/zxywd/9246219