首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python/PyQT:如何截断QLineEdit中的文本

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

Stack Overflow用户
提问于 2016-03-30 05:02:10
回答 3查看 2K关注 0票数 2

我正在为我的问题寻找解决方案。我做错什么了?我从QLineEdit继承了一个名为ExtendedTruncateTextLineEdit的子类。我想要什么?嗯,当你调整窗口大小时,当变得比内容小的时候,我想在一个名为 QLineEdit 的Qwidget中截断一个文本QLineEdit。下面的代码可以工作,但是QLineEdit-widget看起来像一个QLabel。我必须做什么,让下面的代码也绘制我的QLineEdit?

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

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-03-30 19:47:07

这是你可能想要的一个粗略的版本。我在大约10分钟的时间里做好了这个,所以非常粗糙。请注意,在中,这几乎不是一个完整的。它还有几件事要做。在这种情况下,当QLineEdit失去焦点时,文本将被省略。当文本获得焦点时,必须恢复文本。这部分还没有实现。或者更改字体将导致错误的省略,因为QFontMentrics对象将不会被更改,等等。

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() ) )
票数 3
EN

Stack Overflow用户

发布于 2018-03-18 03:32:13

我还需要在一个项目中使用它,所以我将马库斯的回答做得更深入一些,并进行了focusIn和focusOut处理。

由于某些原因,当我调用self.end()self.setCursorPosition(len(self.text())时,两者似乎都没有做太多事情……如果有人能改进这一点,我就知道了。

class ElidingQLineEdit(QtGui.QLineEdit):
    def __init__(self, text= ""):
        super(ElidingQLineEdit, self).__init__()
        self.mText = text
        self.fm = QtGui.QFontMetrics(self.font())

        self.textEdited.connect(self.saveText)
        self.editingFinished.connect(self.elideText)


    def setText(self, text, elide=True):
        self.mText = text
        if elide:
            QtGui.QLineEdit.setText(self, self.fm.elidedText(text, QtCore.Qt.ElideMiddle, self.width()))
        else:
            QtGui.QLineEdit.setText(self, text)


    def resizeEvent(self, rEvent):
        QtGui.QLineEdit.setText(self, self.fm.elidedText(self.mText, QtCore.Qt.ElideMiddle, rEvent.size().width()))
        rEvent.accept()


    def saveText(self, newText):
        self.mText = newText


    def focusInEvent(self, QFocusEvent):
        super(ElidingQLineEdit, self).focusInEvent(QFocusEvent)
        self.setText(self.mText, False)
        self.setCursorPosition(len(self.text()))


    def focusOutEvent(self, QFocusEvent):
        super(ElidingQLineEdit, self).focusOutEvent(QFocusEvent)
        self.setText(self.mText, True)


    def elideText(self):
        QtGui.QLineEdit.setText(self, self.fm.elidedText(self.mText, QtCore.Qt.ElideMiddle, self.width()))
票数 0
EN

Stack Overflow用户

发布于 2018-06-11 04:43:07

对于Spencer和其他用户,我想我有一个解决方案。以下方案适用于以下可执行程序。当用户运行这个程序时,当他输入一个很长的文本时,程序不会缩短文本。此外,如果小部件保持焦点(FocusIn),则QLineEdit()中的长文本不会被截断,但用户可以调整窗口大小。这意味着,只要QLineEdit()保持焦点(FocusIn),文本就不会缩短。只有当QLineEdit()失去焦点(FocusOut)时,文本才会缩短。稍后,当用户决定编辑非常长的文本并在QLineEdit()中单击时,该文本将不带任何缩写显示。

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._show_original_text = False

        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"
                self._show_original_text = True
        if event.type() == QEvent.FocusOut:
            if obj == self.line_edit_text:
                print "You lost focus"
                self._show_original_text = False
                self.line_edit_text.setText(self.font_metrics.elidedText(self.saved_text, self._elide, self.width() -35))
        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.
        '''
        if not self._show_original_text:
            self.line_edit_text.setText(self.font_metrics.elidedText(self.saved_text, self._elide, rEvent.size().width() -35))

        rEvent.accept()

        return


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Example()
    window.show()
    sys.exit(app.exec_())
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36295020

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档