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.setWindowTitle("Right-click to edit the name")
    def create_actions(self):
        self.startEditAct = QtGui.QAction('Edit', self, triggered = self.start_edit_name)
    def setup_context_menu(self, point):
        aMenu = QtGui.QMenu()
    def start_edit_name(self):
        self.nameEdit = QtGui.QLineEdit(self.nameLabel.text())
        self.mainLayout.addWidget(self.nameEdit, 0, 0)
    def finish_edit_name(self):

if __name__ == '__main__':
    import sys

    app = QtGui.QApplication(sys.argv)

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


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.


Leave a comment

Filed under Python

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s