PyQt4 QTextCursor change selectable character - pyqt

How can I change the selectable characters of a QTextCursor, like adding a dot?
For example entering "MyClass" in a QPlainTextEdit the stanza
tc = self.textCursor()
tc.select(QtGui.QTextCursor.WordUnderCursor)
return tc.selectedText()
will returns "MyClass", but entering "MyClass." will returns an empty Qstring!
The problem continues, entering "MyClass.myMeth" will just returns "myMeth", but I need "MyClass.myMeth" :/
Thanks

Ok, I find a solution by replacing the call to WordUnderCursor by :
def textUnderCursor(self):
tc = self.textCursor()
isStartOfWord = False
if tc.atStart() or (tc.positionInBlock() == 0):
isStartOfWord = True
while not isStartOfWord:
tc.movePosition(QtGui.QTextCursor.PreviousCharacter, QtGui.QTextCursor.KeepAnchor)
if tc.atStart() or (tc.positionInBlock() == 0):
isStartOfWord = True
elif QtCore.QChar(tc.selectedText()[0]).isSpace():
isStartOfWord = True
return tc.selectedText().trimmed()

Related

Return statement is not returning

Function PoNanswer should return True or False, it is a loop which can be stoped only when you say Yes,... or No,... and when you say it, it should return. But very strangely it is not returning... How to fix it? thank you in advance)
def PoNanswer(voice_data):
for i in pANSWER_LIST:
if i in voice_data.split():
print('true')
return True
for i in nANSWER_LIST:
if i in voice_data.split():
print('false')
return False
voice_data = record_audio('I did not get it. Please repeat')
PoNanswer(voice_data)
class Command:
def __init__(self, raw_command):
self.raw_command = raw_command
self.key_word = False
self.action_word = False
self.processing()
def processing(self):
print(self.raw_command)
for i in self.raw_command.split():
if i in COMMANDS_LIST:
self.key_word = i
elif i in ACTION_WORD_LIST:
self.action_word = i
if self.key_word == COMMANDS_LIST[0]:
if self.action_word:
speak('ordering...')
main('-//-')
else:
if PoNanswer(record_audio(ADDITIONAL_QUESTIONS[0])):
self.raw_command = self.raw_command + "order"
print("mod")
self.processing()
else:
speak('Okay')
main('-//-')
self.processing()
In this case, I should have used a loop ( while 1: ) instead of calling the same function inside the function.
def PoNanswer(voice_data):
while 1:
for i in pANSWER_LIST:
if i in voice_data.split():
return True
for i in nANSWER_LIST:
if i in voice_data.split():
return False
voice_data = record_audio('I did not get it. Please repeat')
This ^ is fortunately working.
def func(var):
...
func(var)
This ^ wasn't, I have no clue why, but I am happy it is working now))

Display bug when label contain a expression

I have this function who supposed to change the label of polygon (code below), where "nom_com" and "statutpro" are fields in a layer.
def ETIQUETAGE(self):
layer = self.COUCHE_DEPARTEMENT_SELECTIONNEE() #return a vector layer
deco = QgsPalLayerSettings()
deco.enabled = True
isExpression = True
if self.ChoixEtiquetage.currentText() == "COMMUNE":
deco.fieldName = '\'nom :\' +"nom_com"'
if self.ChoixEtiquetage.currentText() == "COMMUNE ET STATUT PROSPECTION":
deco.fieldName = '"nom_com" + \'\\n\' +"statutpro"'
labeler = QgsVectorLayerSimpleLabeling(deco)
layer.setLabeling(labeler)
layer.setLabelsEnabled(True)
layer.triggerRepaint()
When I run it everything ok (i don't have any error), the problem is for the display. The function change the label charateristic in the properties window but there is no display until I press aply in the properties window.
When I put only one argument the display work perfectly. for example
deco.fieldName = "nom_com"
Is there a particular syntax when it's a expression ?
I just see where my error was, it was a syntaxe error.
If the label is expression based we must put
deco.isExpression
for the plugin to display something in the canvas
def ETIQUETAGE(self):
layer = self.COUCHE_DEPARTEMENT_SELECTIONNEE() #return a vector layer
deco = QgsPalLayerSettings()
deco.enabled = True
deco.isExpression = True
if self.ChoixEtiquetage.currentText() == "COMMUNE":
deco.fieldName = "concat('nom : ', nom_com)"
if self.ChoixEtiquetage.currentText() == "COMMUNE ET STATUT PROSPECTION":
deco.fieldName = "concat('nom : ', nom_com, '\\n', 'Statut prospection : ', statutpro)"'
labeler = QgsVectorLayerSimpleLabeling(deco)
layer.setLabeling(labeler)
layer.setLabelsEnabled(True)
layer.triggerRepaint()
hope it will help people

How to go to first line of a function if a condition is not satisfied in python?

I want to got First line of the function goToSignUpActivit() if isAllInputValid == False
from CustomUtil import *
from Register import *
def goToSingUpActivity():
fName = input("Enter your First Name:")
lName = input("Enter your last name:")
mobileNum = input("input your mobile number")
role = input("Select your role s: for staff p: for patient:")
isFNameValid = validateInput(fName)
isLNameValid = validateInput(lName) // this function in CustomUtil package
isRoleValid = False
if (role in ["s","p","S","P"]):
isRoleValid = True
isMobileNumValid = validateMobilNum(mobileNum)// this function in CustomUtil package
isAllInputValid = False
if (isFNameValid and isLNameValid and isRoleValid and isMobileNumValid) :
isAllInputValid = True
if (isAllInputValid) :
isAllInputValid = True
if role in ["s","S"]:
registerAsStaff(fName,lName,mobileNum)// this function in Register package
return
elif role in ["p","P"]:
registerAsPatient(fName,lName,mobileNum)// this function in Register package
return
while(not isAllInputValid):
if(input("you want to exit y or n:") in ["y","Y"]):
return
goToSingUpActivity()
Above code put goToSingUpActivity() into the stack while isAllInputValid become true.
After I enter all input correctly stack pop goToSingUpActivity() one bye one.
What I need here is after isAllInputValid becomes true, clear all goToSingUpActivity() from stack.
If above solution not possible, is there any other way to modifie the code?
Edit: I got a solution by making isAllInputValid global and put the while loop outside the function after calling goToSingUpActivity().
You can use a while statement (WARNING to don't create a while(true), give to the user an opportunity to cancel his action !).
def goToSingUpActivity():
 isAllValid = False
 while(!isAllValid):
#your inputs stuff
if(isFNameValid and isLNameValid and isRoleValid and isMobileNumValid):
   isAllValid = True
 #rest of the function

UnboundLocalError: Referenced before assignment local variable 'emoji_count'

Hi I had this niggling issue with a cog (bot module) on writing and I keep getting an UnboundLocalError: Referenced before assignment I'm aware this is a very common issue however I'm not seeing the issue.
The module works but every time a post is reacted to with a star it throws off this error in the console.
The error is:
starboard.py", line 22, in on_reaction_add
if emoji_count > 0: #if 0 then 1 counts
UnboundLocalError: local variable 'emoji_count' referenced before assignment
The area of more specific I'm looking at is:
async def on_reaction_add(self, reaction, user):
for guild in self.bot.guilds:
chan = get(guild.channels, name="starboard")
if chan:
if reaction.message.author == user:
return
if reaction.emoji == '⭐' or reaction.emoji == '🌟':
if not chan:
return
emoji_count = reaction.message.reactions[0].count
msg = f"{reaction.message.author.mention} your post was posted to starboard."
em = discord.Embed(color=discord.Color(random.randint(0x000000, 0xFFFFFF)))
display = f"""{reaction.message.content}"""
em.description = display
em.set_author(name=reaction.message.author.name, icon_url=reaction.message.author.avatar_url)
em.set_footer(text=f"Posted in: #{chan.name}")
em.timestamp = dt.datetime.utcnow()
try:
img_url = reaction.message.attachments[0].url
except IndexError:
img_url = None
if not img_url:
try:
img_url = reaction.message.embeds[0].url
except IndexError:
img_url = None
if img_url:
em.set_image(url=str(img_url))
if emoji_count > 0: #if 0 then 1 counts
if not chan:
return
await chan.send(msg)
await chan.send(embed=em)
If anyone can tell me whats going on here and where I'm going wrong I'd much appreciated it.
When your if statement condition in if reaction.emoji == '⭐' or reaction.emoji == '🌟': doesn't return True , emoji_count won't get initialized
(emoji_count = reaction.message.reactions[0].count)
So when you try to use it a couple of lines underneath in if emoji_count > 0: it causes
local variable 'emoji_count' referenced before assignment, which is exactly what it says, python not being able to find your variable's initialization anywhere in the code that ran
I think what is being said here is the following:
if emoji_count >= 2 :
if not chan:
return True
As said in the previous answers it should be
if reaction.emoji == '⭐' or reaction.emoji == '🌟' is True:

Get id of a record with the lowest sequence

I have this class
name = fields.Char("Name")
sequence = fields.Integer("Sequence")
description = fields.Text("Description")
I need a search method to find the id with lower sequence
res = self.env['your.model'].search([], limit=1, order='sequence desc')
should to the trick
I think this search function would do the trick.
def _find_register(self, operator, value):
lowest_sequence_id = False
lowest_sequence = False
for state in self.env['ags.traffic.operation.state'].search([('id','>',0)]):
if not lowest_sequence:
lowest_sequence_id = state.id
lowest_sequence = state.sequence
elif state.sequence < lowest_sequence:
lowest_sequence = state.sequence
return [('id', '=', lowest_sequence_id)]

Resources