Making a QTextEdit capital

被刻印的时光 ゝ 提交于 2019-12-13 05:12:15

问题


I am trying to make all text in a QTextEdit capital, but currently am failing. This is my code and it does nothing.

void MainWindow::on_actionCapital_triggered()
{
    QTextCharFormat capital2;
    capital2.setFontCapitalization(QFont::AllUppercase);
    ui->textEdit->setCurrentCharFormat(capital2);
}

I am a java coder, so c++ is not my strong point

I also tried the following code with no success:

QFont font = ui->textEdit->font();
font.setCapitalization(QFont::AllUppercase);
ui->textEdit->setFont(font);

Can someone please point me to the right direction?


回答1:


I figured it out not the most elegant solution, but it will do its job:

void MainWindow::on_actionCapital_triggered()
{
    QTextCursor c = ui->textEdit->textCursor();
    int current = c.position();
    if(capital)
    {
        QTextCharFormat capital2;
        capital2.setFontCapitalization(QFont::MixedCase);
        ui->textEdit->selectAll();
        ui->textEdit->setCurrentCharFormat(capital2);
        capital = false;
    }
    else
    {
        QTextCharFormat capital2;
        capital2.setFontCapitalization(QFont::AllUppercase);
        ui->textEdit->selectAll();
        ui->textEdit->setCurrentCharFormat(capital2);
        capital = true;
    }
    c = ui->textEdit->textCursor();
    c.setPosition(current);
    c.setPosition(current, QTextCursor::KeepAnchor);
    ui->textEdit->setTextCursor(c);
}

With this code you can switch between all Upper case and mixed case. For some reason the setCurrentCharFormat only works when the text is selected. So I had to get the current cursor position and then select all apply the FontCapitalization and then set the cursor back to where it was.



来源:https://stackoverflow.com/questions/19038897/making-a-qtextedit-capital

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!