Do you mean that it does *not *work when the QTextEdit is *out of* focus?
Also a couple suggestions for that example code:

A keyPressEvent() will always receive a QKeyEvent, so you don't need to
check for it. But if you want to check an event, it is better to use this
form:
    if event.type() == event.KeyPress
(You can reference all the QEvent types here:
http://qt-project.org/doc/qt-4.8/qevent.html#Type-enum)

For testing the key, if you are going to actually use the key() method of
the event, it is best to compare it to the actual Qt.Key constants. Here
are two approaches:

# I might even make this an instance attribute during my __init__ so it
does not have to
# define it again each time.
keyPossibilities = set([Qt.Key_0, Qt.Key_1, ...])
# then just test if the key is in the set, which is fast
if event.key() in keyPossibilities:
   ...

Or you can match against the text() value:
keyPossibilities = set('0123456789')
if str(event.text()) in keyPossibilities:
    ...

And lastly, It might be best if you by default always ignore the event if
you don't want to handle it. There is a bit of logic in there right now
where it can fall through and be accepted, if say there where no children
found with findChildren(), or the key was not < 255. So maybe do:

if foo:
    event.accept()
    return

event.ignore()
# or even call the superclass to have it do the default
# super(MyClass, self).keyPressEvent(event)


-- justin



On Mon, Dec 3, 2012 at 11:13 PM, Sudeepth Patinjarayil
<[email protected]>wrote:

> Hi All ,
>
> I am facing a problem in KeyPressEvent. The KeyPressEvent code is as
> follows.
>
> def keyPressEvent(self, event):
>         keyPossiblities = ['0','1','2','3','4','5','6','7','8','9']
>         if type(event) == QtGui.QKeyEvent:
>             if self.findChildren(QtGui.QTabWidget,"TAB_CScomment") :
>                 if event.key() < 255 :
>                     if chr(event.key())in keyPossiblities :
>                         prvTxt = self.textFLD
> [str(self.clickedFileName)].toPlainText()
>                         self.textFLD
> [str(self.clickedFileName)].setHtml("%s %s" % (prvTxt,
> self.preDefComments[chr(event.key())]))
>                     event.accept()
>         else:
>             event.ignore()
>
> It actually fills a QTextEdit with some comments from a text file when the
> user press NUM keys in keyboard (0-9). Everything is working fine as
> excepted. But when the text is on focus the KeyPressEvent is not working.
> Can anyone give me a solution to overcome this issue.
>
> Thanks and Regards,
> Sudeepth Patinjarayil.
>
> --
> view archives: http://groups.google.com/group/python_inside_maya
> change your subscription settings:
> http://groups.google.com/group/python_inside_maya/subscribe
>

-- 
view archives: http://groups.google.com/group/python_inside_maya
change your subscription settings: 
http://groups.google.com/group/python_inside_maya/subscribe

Reply via email to