Yore
Yore

Reputation: 430

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:

Initial Cursor Color

To this:

enter image description here

Thanks.

Edit2: Final Look

enter image description here

Upvotes: 5

Views: 8485

Answers (2)

thuga
thuga

Reputation: 12901

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);

Upvotes: 7

Jablonski
Jablonski

Reputation: 18504

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):

enter image description here

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.

Upvotes: 4

Related Questions