Thursday, April 3, 2014

PyQt QTextEdit - Get the current line number when/where the mouse is pressed.

Here is an easy way to get the current line number in QTextEdit when/where you press mouse. This way doesn't derive QTextEdit or install event filter. This way just delegates mouseReleaseEvent to your event handler.

import sys
from PyQt4 import QtCore, QtGui

class MainWindow (QtGui.QMainWindow):

    def __init__ (self, parent=None):
        super (MainWindow, self).__init__(parent)

        self.BuildEditor ()
        self.setCentralWidget(self._Editor)
        self.setWindowTitle("Get line number in QTextEdit when mouse is pressed.")

    def BuildEditor (self):
        self._Editor = QtGui.QTextEdit ()
        self._Editor.setReadOnly (True)
        self._Editor.mouseReleaseEvent = self.MyMouseReleaseEvent
        
        Font = QtGui.QFont ()
        Font.setFamily ('Courier')
        Font.setFixedPitch (True)
        Font.setPointSize (10)
        self._Editor.setFont (Font)

        Text = "aaaaaaaaaaaaaaaaaaaaaaa\n"
        Text += "bbbbbbbbbbbbbbbbbbbbbbb\n"
        Text += "ccccccccccccccccccccccc\n"
        Text += "ddddddddddddddddddddddd\n"
        self._Editor.setPlainText (Text)
       
    def MyMouseReleaseEvent (self, Event):
        print ("Release the mouse.")
        Pos = Event.pos()
        print ("Pos = (%d, %d)" % (Pos.x (), Pos.y ())) 
        Cursor = self._Editor.cursorForPosition (Pos)
        X = Cursor.columnNumber();
        Y = Cursor.blockNumber();        
        print ("Cursor = (%d, %d)" % (X, Y))    
        
if __name__ == '__main__':
    App = QtGui.QApplication (sys.argv)
    Window = MainWindow ()
    Window.resize (640, 512)
    Window.show ()
    sys.exit (App.exec_())

No comments:

Post a Comment