Monday, April 14, 2014

PyQt addToolBarBreak () - Create Two Toolbars

We can use addToolBarBreak () to create two toolbars. One is followed by another with a line break. Here is an example of PyQt.

import sys
from PyQt4 import QtGui

class MyMainWindow (QtGui.QMainWindow):
   
    def __init__ (self):
        super (MyMainWindow, self).__init__ ()
       
        Toolbar1 = self.addToolBar ("")
        self.addToolBarBreak ()
        Toolbar2 = self.addToolBar ("")
       
        Cb = QtGui.QComboBox ()
        Toolbar1.addWidget (Cb)
        Cb = QtGui.QComboBox ()
        Toolbar1.addWidget (Cb)

        Cb = QtGui.QComboBox ()
        Toolbar2.addWidget (Cb)
        Cb = QtGui.QComboBox ()
        Toolbar2.addWidget (Cb)
       
        self.setGeometry (300, 300, 300, 200)
        self.setWindowTitle ('Multiple Toolbars')
        self.show ()
       
def main():
    App = QtGui.QApplication (sys.argv)
    MainWindow = MyMainWindow ()
    sys.exit (App.exec_ ())

if __name__ == '__main__':
    main()



We can also use addToolBarBreak () to create multiple toolbars.

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_())