Python/PyQT:如何截断QLineEdit中的文本?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (140)
import sys
from PyQt4.QtCore import Qt
from PyQt4.QtGui import QApplication,\
                        QLineEdit,\
                        QLabel,\
                        QFontMetrics,\
                        QHBoxLayout,\
                        QVBoxLayout,\
                        QWidget,\
                        QIcon,\
                        QPushButton,\
                        QToolTip,\
                        QBrush,\
                        QColor,\
                        QFont,\
                        QPalette,\
                        QPainter

qt_app = QApplication(sys.argv)

class Example(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.setMinimumWidth(100)

        self.init_ui()


    def init_ui(self):
        v_layout = QVBoxLayout()
        v_layout.addStretch(1)

        lbl = ExtendedTruncateTextLabel("This is a really, long and poorly formatted runon sentence used to illustrate a point", self)
        #lbl.setText("This is a really, long and poorly formatted runon sentence used to illustrate a point")

        lbl_1 = ExtendedTruncateTextLabel(self)
        lbl_1.setText("Dies ist ein normaler Text")

        l_text = ExtendedTruncateTextLineEdit()
        l_text.setText("In the widget namend QLineEdit is also a very long text")


        v_layout.addWidget(lbl)
        v_layout.addWidget(lbl_1)
        v_layout.addWidget(l_text)

        self.setLayout(v_layout)

    def run(self):
        self.show()
        qt_app.exec_()

class ExtendedTruncateTextLineEdit(QLineEdit):   
    def __init(self, parent):
        QLineEdit.__init__(self, parent)

    def paintEvent(self, event):

        """ Handle the paint event for the title bar.

        This paint handler draws the title bar text and title buttons.

        """
        super(ExtendedTruncateTextLineEdit, self).paintEvent(event)
        painter = QPainter(self)

        metrics = QFontMetrics(self.font())
        elided  = metrics.elidedText(self.text(), Qt.ElideMiddle, self.width())

        painter.drawText(self.rect(), self.alignment(), elided)

if __name__ == '__main__':
    app = Example()
    app.run()
提问于
用户回答回答于
class ElidingLineEdit( QLineEdit ) :
    """Eliding text lineedit
    """

    def __init__( self, text = QString(), parent = None ) :
        """Class initialiser
        """

        QLineEdit.__init__( self, parent )
        self.mText = text;

        self.fm = QFontMetrics( self.font() )

        self.textEdited[ QString ].connect( self.saveText )
        self.editingFinished.connect( self.shortenText )

    def setText( self, txt ) :
        """setText( QString ) -> None

        Override the QLineEdit::setText to display the shortened text

        @return None
        """

        QLineEdit.setText( self, self.fm.elidedText( self.mText, Qt.ElideRight, self.width() ) )

    def resizeEvent( self, rEvent ) :
        """resizeEvent( QResizeEvent ) -> None

        Override the resizeevent to shorten the text

        @return None
        """

        QLineEdit.setText( self, self.fm.elidedText( self.mText, Qt.ElideRight, rEvent.size().width() ) )

        rEvent.accept()

    def saveText( self, newText ) :
        """saveText() -> None

        Save the text as it is changing

        @return None
        """

        self.mText = newText

    def shortenText( self ) :
        """saveText() -> None

        Save the text as it is changing

        @return None
        """

        QLineEdit.setText( self, self.fm.elidedText( self.mText, Qt.ElideRight, self.width() ) )
用户回答回答于
import sys
from PyQt4.QtCore import Qt, QEvent, QString
from PyQt4.QtGui import (QApplication, QLineEdit, QFontMetrics, QVBoxLayout,
                        QWidget, QPushButton)

class Example(QWidget):
    def __init__(self, elide = Qt.ElideMiddle,  parent = None):
        QWidget.__init__(self, parent)

        self.setMinimumWidth(80)

        self.font_metrics = QFontMetrics(self.font())

        self.saved_text = ""

        self._elide = elide

        self.init_ui()

    def init_ui(self):
        #   Create an instance of QLineEdit()
        self.line_edit_text = QLineEdit()
        self.line_edit_text.setPlaceholderText("Hell world I am here where you are")
        #   We must implement the eventFilter method
        #   and enable this property to the widgets that are needed with
        self.line_edit_text.installEventFilter(self)

        #   Create an instance of QPushButton()
        self.push_button = QPushButton("Just click me, nothing will happen.")
        self.push_button.installEventFilter(self)

        #   Add the both widgets to the layout, that is created.
        v_layout = QVBoxLayout()
        v_layout.addStretch(1)
        v_layout.addWidget(self.line_edit_text)
        v_layout.addWidget(self.push_button)
        self.setLayout(v_layout)

        #   Set a slot, connect() the textChanged-slot to the handle_text_change()-method.
        self.line_edit_text.textEdited[QString].connect(self.save_text)

    def eventFilter(self, obj, event):
        #   The eventFilter method has as information
        #   the object and type of event. So we have to
        #   listen to the focus events.
        if event.type() == QEvent.FocusIn:
            if obj == self.line_edit_text:
                self.line_edit_text.setText(self.saved_text)
                print "You clicked in the LineEdit"
        if event.type() == QEvent.FocusOut:
            if obj == self.line_edit_text:
                print "You lost focus"
                self.line_edit_text.setText(self.font_metrics.elidedText(self.saved_text, self._elide, self.width() -10))
        return super(QWidget, self).eventFilter(obj, event)

    def save_text(self, new_text):
        '''
            NOTICE:
            =======
            Implement the saveText()-method to save the text as it is changing.

            PARAMETERS:
            ===========
            :new_text   -   The given text have to save.

            :return     -   Nothing is returned. The statement 'return'
                            terminates a function. That makes sure that the
                            function is definitely finished.
        '''
        self.saved_text = new_text

        return

    def resizeEvent(self, rEvent):
        '''
            NOTICE:
            =======
            Override the resizeevent()-method of QLineEdit()-class to shorten the text.

            PARAMETERS:
            ===========
            :rEvent     -   The given QResizeEvent class contains event
                            parameters for resize events - for example accept()-method.

            :return     -   Nothing is returned. The statement 'return'
                            terminates a function. That makes sure that the
                            function is definitely finished.
        '''
        self.line_edit_text.setText(self.font_metrics.elidedText(self.saved_text, self._elide, rEvent.size().width() -10))

        rEvent.accept()

        return


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Example()
    window.show()
    sys.exit(app.exec_())

我有个小问题。如果文本位于中间,则左侧的文本将无法正确显示。

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励