简体   繁体   中英

Qt 5.3 QPlainTextEdit Change the QTextCursor color

I would like to change the cursor color under the QPlainTextEdit widget. I was able to set it's width to 6 , but I want to change the color or it. Is it possible ?

QFontMetrics fm(font());
setCursorWidth( fm.averageCharWidth() );
//setCursorColor is what I need.

Thanks.

Edit:

Including the images to exemplify...

From this:

初始光标颜色

To this:

在此输入图像描述

Thanks.

Edit2: Final Look

在此输入图像描述

You can use QTextCharFormat to set the color of the text in your QPlainTextEdit . Use the QTextCharFormat::setForeground to set the color. Then use a stylesheet to change the color of the cursor by using the color property.

QPlainTextEdit *p_textEdit = new QPlainTextEdit;
p_textEdit->setStyleSheet("QPlainTextEdit{color: #ffff00; background-color: #303030;"
                          " selection-background-color: #606060; selection-color: #ffffff;}");
QTextCharFormat fmt;
fmt.setForeground(QBrush(QColor(255,255,255)));
p_textEdit->mergeCurrentCharFormat(fmt);

Edit

You can change caret color with next stylesheet:

ui->plainTextEdit->setStyleSheet(
            "QPlainTextEdit"
            "{"
            "color: yellow;"
            "}"
            );

But there is another problem, all text becomes with this color too. How to set new color to text but left old color for caret? I found this solution, maybe not the best: use html code:

ui->plainTextEdit->appendHtml("<font color = \"red\"> Sample Text</font>");

Result (as you want original color for caret and for text):

在此输入图像描述

Now text has needed color but caret has special color. It is solution, but it is a little dirty for me, if someone will find better way to change color of text without changing caret color, please tell this.

You can change only main cursor under widget:

QPixmap pix("pathToPixmap");
QCursor cur(pix);
ui->plainTextEdit->viewport()->setCursor(cur);

Qt has next embedded cursors: http://qt-project.org/doc/qt-5/qt.html#CursorShape-enum

Qt has not any cursor with specific color, so you should use you own pixmap. You can use image with simple arrow but with another color (if it has alpha-channel then it is better)

There are many different cursors in the web.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM