setBold(True) works only if textcursor has not been moved, why?

230 views Asked by At

I want to set the selectedPart of the text bold. I wanna do this depending on the character's format. With my code, I can detect that format, but setting bold does not work. If I uncomment those 2 commented lines, and comment all the lines below (accept the last 5 lines, ofcourse), I can set the code bold.

This code is fully working, you can test it out and perhaps you have an idea. You select text by mouse, and then invoke the set-bold-method with CTRL+B.

(My ideas on it: The problem seems to depend on the fact that i move the QTextCursor to get informations about the character format at the other end of the selection. Perhaps there is an easier way to get that info, but I only figured out this one. But I don't get why the movement of the textCursor is bad, because it still seems to have a valid selection and I assume the font=self.currentFont() still to work.)

from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4 import QtCore, QtGui
import sys,os

class test(QTextBrowser):
    def __init__(self, parent=None):
        super(QTextBrowser, self).__init__(parent=None)
        self.setHtml("""
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII<br>IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII<br>
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII<br>IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII<br>
IIIIIIIIIIIII<b>IIIIIIIIIIIIIIIIIIIIIIII<br>IIIIIIIIIIIIIIIIIII</b>IIIIIIIIIIIIIIIIIIIIII<br>
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII<br>IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII<br>
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII<br>IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII<br>
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII
""")
        self.setReadOnly(False)
        self.resize(400,400)
        self.keylist=[]
        self.installEventFilter(self)        
    def setBold(self):       
            font  = self.currentFont()
            cur=self.textCursor()
##            font.setBold(True)
##            self.setCurrentFont(font)

            if cur.hasSelection():
                print("Before: there is selected text.")
            else:
                print("Before: there is NO selected text.")

            print("The anchor position is "+str(self.textCursor().anchor()))
            print("The cursor position is "+str(self.textCursor().position()))

            anchorPos=cur.anchor()
            currentPos=cur.position()

            if anchorPos>currentPos:
                direction="rtl" #rigth to left selection
            else:
                direction="ltr" #left to right selection

            print("The selection direction is "+str(direction))
            oldPosition=cur.position()

            if direction=="ltr":
                selectedTextEnd = cur.charFormat()
                cur.setPosition(cur.anchor(), QtGui.QTextCursor.KeepAnchor)
                self.setTextCursor(cur)
                selectedTextBeginning = cur.charFormat()

            else:
                selectedTextBeginning = cur.charFormat()
                cur.setPosition(cur.anchor(), QtGui.QTextCursor.KeepAnchor)
                self.setTextCursor(cur)
                selectedTextEnd = cur.charFormat()

            cur.setPosition(oldPosition, QtGui.QTextCursor.KeepAnchor)

            if cur.hasSelection():
                print("After: there is selected text.")
            else:
                print("After: there is NO selected text.")

            print("fontWeight begin = "+str(selectedTextBeginning.fontWeight()  )  )
            print("fontWeight end = "+str(selectedTextEnd.fontWeight()  )  )

            if selectedTextBeginning.fontWeight()==50 and selectedTextEnd.fontWeight()==75:
                print("Check 1")
                font.setBold(False)
                self.setCurrentFont(font)
            if selectedTextBeginning.fontWeight()==75 and selectedTextEnd.fontWeight()==75:
                print("Check 2")
                font.setBold(False)
                self.setCurrentFont(font)
            if selectedTextBeginning.fontWeight()==50 and selectedTextEnd.fontWeight()==50:
                print("Check 3")
                font.setBold(True)
                self.setCurrentFont(font)
            if selectedTextBeginning.fontWeight()==75 and selectedTextEnd.fontWeight()==50:
                print("Check 4")
                font.setBold(True)
                self.setCurrentFont(font)

            cur.setPosition(oldPosition, QtGui.QTextCursor.MoveAnchor)

    def eventFilter(self, target, event):            
        if event.type()==QEvent.KeyPress: 
            if "Ctrl" in self.keylist:
                self.keylist.append(str(event.key()))                
            if event.key()==Qt.Key_Control:
                self.keylist.append("Ctrl")
        return False

    def processmultikeys(self,keyspressed):
        if keyspressed[0]=="Ctrl" and keyspressed[1]=="66": #ctrl and B
            self.setBold()

    def keyReleaseEvent(self,event):
        if len(self.keylist)==2:
            self.processmultikeys(self.keylist)
            del self.keylist[-1]
        else:
            self.keylist=[]

if __name__ == '__main__':
    app=QApplication(sys.argv)
    a = test()
    a.show()
    app.exec_()
0

There are 0 answers