使用Qt开发文本编辑器(二):标签页式文档实现

Qt中相关的类

标签页俗称Tab页,Qt提供了QTableWidget用于创建基于Tab页式的文档。使用QTableWidget,我们可以很方便得添加和删除Tab、设置和获取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

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值