PyQt Editable Label

import sys, os
from PyQt4 import QtCore, QtGui

class AddressBook(QtGui.QWidget):
    def __init__(self, parent=None):
        super(AddressBook, self).__init__(parent)

        self.nameLabel = QtGui.QLabel("untitled")
        
        self.mainLayout = QtGui.QGridLayout()
        self.mainLayout.addWidget(self.nameLabel, 0, 0)
        
        self.setLayout(self.mainLayout)
        
        self.setWindowTitle("Right-click to edit the name")
        
        self.create_actions()
        self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.setup_context_menu)
        
    def create_actions(self):
        self.startEditAct = QtGui.QAction('Edit', self, triggered = self.start_edit_name)
        
    def setup_context_menu(self, point):
        aMenu = QtGui.QMenu()
        aMenu.addAction(self.startEditAct)
        aMenu.exec_(self.mapToGlobal(point)) 
        
    def start_edit_name(self):
        self.nameEdit = QtGui.QLineEdit(self.nameLabel.text())
        self.mainLayout.addWidget(self.nameEdit, 0, 0)
        self.nameEdit.returnPressed.connect(self.finish_edit_name)
        
    def finish_edit_name(self):
        self.nameLabel.setText(self.nameEdit.text())
        self.nameEdit.hide()

if __name__ == '__main__':
    import sys

    app = QtGui.QApplication(sys.argv)

    addressBook = AddressBook()
    addressBook.show()
    addressBook.move(100, 100)
    addressBook.resize(320, 100)

    sys.exit(app.exec_())

We have a label can put some text there. That is OK until we want to change the text. Using a line edit instead could be an option, but we want the text stay there most of the time untouchable.

This problem can be solved by a simple trick. Right-click and choose the ‘Edit’ menu, a line edit will be placed over the label. Press enter when finished the editing. That will trigger a function to change the label text and hide the line edit over it.

This also brings a minimal example about how to create context (right-click-to-pull-down) menus as well as how to use signal and connect.

Get the source.

Advertisements

Leave a comment

Filed under Python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s