Can I retrieve the text color (or background color) of the character at the text cursor from QTextEdit? - linux

I have a QTextEdit window with words and letters displayed in several colors. I want to be able to retrieve the color of each part of the text when processing the contents of the window. My attempt so far has been to save the entire contents as an html file and then parse through that to extract only the text with the color information. This is very cumbersome and difficult. I would much prefer to process the text using the QTextCursor if I could retrieve the color of the text at the cursor position. I have searched for the appropriate function but have not found one.
Is there a function to retrieve the color (or the format) at the QTextCursor position?
Or alternatively is there a way to retrieve each contiguous section of words and/or characters that have the same color (or format) with the format information?

Well I have found a way to do what I wanted. Here is the relevant code:
QTextCursor tc = qte->textCursor();
tc.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
while(tc.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor))
{
QTextCharFormat tcf = tc.charFormat();
int bg = tcf.background().color().rgb();
int fg = tcf.foreground().color().rgb();
printf("bg=%x fg=%x\n", bg, fg);
}
any comments or improvements are welcome.
[Corrected above]: I originally had
QColor bg = tcf.background().color().rgb();
QColor fg = tcf.foreground().color().rgb();
but with .rgb() on the end, it converts QColor to int.

Related

Highlight the word in ppt using python-pptx

I want to read ppt and highlight certain word(background color added if background color is not possible then change the font color) in the slide. I am able to do it at sentence level i.e. if that word is contain in paragraph then it will change the font color of whole text but i want to change the color of that word only.
How about the following for highlighting?
def set_highlight(run, color):
# get run properties
rPr = run._r.get_or_add_rPr()
# Create highlight element
hl = OxmlElement("a:highlight")
# Create specify RGB Colour element with color specified
srgbClr = OxmlElement("a:srgbClr")
setattr(srgbClr, "val", color)
# Add colour specification to highlight element
hl.append(srgbClr)
# Add highlight element to run properties
rPr.append(hl)
return run
It's hacking the XML but for highlighting (text background) that's what you have to do.

Format text of mark_text in Altair

I'm trying to create a chart somewhat along the lines of the Multi-Line Tooltip example, but I'd like to format the string that is being printed to have some text added at the end. I'm trying to modify this part:
# Draw text labels near the points, and highlight based on selection
text = line.mark_text(align='left', dx=5, dy=-5).encode(
text=alt.condition(nearest, 'y:Q', alt.value(' '))
)
Specifically, rather than 'y:Q' I want something along the lines of 'y:Q' + " suffix". I've tried doing something like this:
# Draw text labels near the points, and highlight based on selection
text = line.mark_text(align='left', dx=5, dy=-5).encode(
text=alt.condition(nearest, 'y:Q', alt.value(' '), format=".2f inches")
)
Alternatively, I've tried:
# Draw text labels near the points, and highlight based on selection
y_fld = 'y'
text = line.mark_text(align='left', dx=5, dy=-5).encode(
text=alt.condition(nearest, f"{y_fld:.2f} inches", alt.value(' '))
)
I think I see why those don't work, but I can't figure out how to intercept the value of y and pass it through a format string. Thanks!
I think the easiest way to do this is to calculate a new field using transform_calculate to compute the label that you want.
Using the example from the documentation, I would change the text chart like this:
text = line.mark_text(align='left', dx=5, dy=-5).encode(
text=alt.condition(nearest, 'label:N', alt.value(' '))
).transform_calculate(label='datum.y + " inches"')
That leads to this chart:
If you want more control, you could change the dataset with pandas beforhand. Be sure to set the type to Nominal (and not Quantitative) otherwise you would get NaNs in the tooltips.

In PyQt QTreeView item, how to set color for specific column blocks

With PyQt4 based QTreeView, I've created 2 xml tree widgets. From both the trees, want to compare selected items and highlight the difference. For e.g.,
Left String : "CompareString"
Right String : "ComPareStringRight"
The observations of the diff :
Left[0:2] is same as Right[0:2]
Left[3:3] differs with Right[3:3]
Left[4-12] is same as Right[4-12]
Right[13-17] is not present in Left
Now, want to set colors according to :
matching characters - default
Differing characters - Orange
Added characters - Green
Deleted characters - Red
How can I implement this? Unable to find any reference implementation to pick up from. Pls suggest a way forward.
class QCustomDelegate (QItemDelegate):
global showDiffPaint
def paint (self, painterQPainter, optionQStyleOptionViewItem, indexQModelIndex):
column = indexQModelIndex.column()
if showDiffPaint == 1:
QItemDelegate.paint(self, painterQPainter, optionQStyleOptionViewItem, indexQModelIndex)
else:
QItemDelegate.paint(self, painterQPainter, optionQStyleOptionViewItem, indexQModelIndex)
After digging, found it useful to convert text into html, and present as below.
However, found bugs due to " and < and > characters display. which I think I need to escape somehow...
options = QStyleOptionViewItemV4(option)
doc = QTextDocument()
doc.setHtml(txt1)
doc.setTextWidth(option.rect.width())
style = QApplication.style()
style.drawControl(QStyle.CE_ItemViewItem, options, painter)
ctx = QAbstractTextDocumentLayout.PaintContext()
textRect = style.subElementRect(QStyle.SE_ItemViewItemText,
options)
painter.translate(textRect.topLeft())
painter.setClipRect(textRect.translated(-textRect.topLeft()))
doc.documentLayout().draw(painter, ctx)

Highlight predetermined locations in textbox

I have been using python 3.4 and tkinter to create an application to parse logs and format data and display results in a text widget. I would like to highlight text that is located at a known position on each line in the text window. I have seen similar highlighting questions regarding highlighting text in text widgets on this site and it has been very helpful.
My problem is that I don't need to search for the string or characters to highlight. I have the locations that I want to highlight and it could be any character in that location including white space. For example: I would like to highlight positions 0, 20, 40 on each line (eg: index 1.0, 1.20, 1.40, 2.0, 2.20, etc).
Since it is large files being written to the textbox I have to do this for the entire scrollable text window, so I need to maintain the textbox line number position.
When referring to a location in a text widget, you can append modifiers to indicate relative positioning. For example, given the position "1.0", the next position can be identified as "1.0+1c" (or "1.0+1char"). So, to highlight a single character at a given offset, make the start of the range the offset, and the end of the range one character greater.
Here's a quick hack that takes one or more "positions" and highlights that position on each line:
def highlight(text, tag, *positions):
last_line = int(text.index("end-1c").split(".")[0])
for linenumber in range(1, last_line+1):
line = text.get("%s.0" % linenumber, "%s.0 lineend-1c" % linenumber)
line_length = len(line)
for pos in positions:
if pos <= line_length:
start = "%s.%s" % (linenumber, pos)
end = start + "+1c"
text.tag_add(tag, start, end)
usage:
text = Text(...)
text.tag_configure("highlight", ...)
...
highlight(text, "highlight", 0, 20, 40)

How to determine the color of the one part of the text in cell by Apache POI

I have Excel table.
In the cell we can have text (for example text1;text2) and part 1 (text1) of this text will have black color,
but another one (text2) have, for example, red color.
For read Excel file I use Apache POI.
Could you please ask how to determine the color (which in our case is red) of THAT second part of the text.
For determination of the whole text in the cell I use now this code:
HSSFCellStyle cellStyle = (HSSFCellStyle) currentCell.getCellStyle();
short cellColor = cellStyle.getFont(currentCell.getSheet().getWorkbook()).getColor();
I don't know if it determinate it correct
You need to fetch the cell's contents as a RichTextString and then get the formatting information from that
For HSSF, your code would want to be something like:
HSSFRichTextString richTextString = hssfCell.getRichStringCellValue();
for (int i=0; i<richTextString.0,r.numFormattingRuns(); i++) {
if (richTextString.getFontAtIndex(i) == HSSFRichTextString.NO_FONT) {
// Default cell formatting rules apply to this bit
} else {
HSSFFont font = workbook.getFontAt(richTextString.getFontAtIndex(i));
// This bit of the string has the above font
}
}
You can use methods like getIndexOfFormattingRun() to work out where in the string the font changes

Resources