当我更改主窗口大小时,如何隐藏或剪切Qwidget()文本

时间:2016-01-29 08:40:30

标签: python-2.7 qt4 pyqt4

编辑:当我更改主窗口大小时,我需要剪切包含在QLabel()中的QStatusBar()文本以适合表单的大小。如下图所示。

from PyQt4.QtGui import * 
from PyQt4.QtCore import * 
import sys

class MyMainWindow(QMainWindow): 

    def __init__(self):
        QMainWindow.__init__(self)

        self.setCentralWidget(QLabel("main widget"))

        statusBar = QStatusBar()
        self.setStatusBar(statusBar)

        statusBar.addWidget(QLabel("first message"))
        statusBar.addWidget(QLabel("second message"))
        statusBar.addWidget(QLabel("a thrid long long long long long message"))

app = QApplication(sys.argv)  
window = MyMainWindow()    
window.show()
sys.exit(app.exec_())

simulation

1 个答案:

答案 0 :(得分:1)

关键是在标签上设置适当的最小宽度,然后允许它们调整小于文本宽度的大小。但是,这将简单地裁剪右侧的文本,而不是将其删除(即最后出现...)。

博文Status bar and elided label解释了如何获取删除文本,但解决方案是用C ++编写的。下面是用PyQt4编写的等效版本:

import sys
from PyQt4 import QtCore, QtGui

class ElidedLabel(QtGui.QLabel):
    _width = _text = _elided = None

    def __init__(self, text='', width=40, parent=None):
        super(ElidedLabel, self).__init__(text, parent)
        self.setMinimumWidth(width if width > 0 else 1)

    def elidedText(self):
        return self._elided or ''

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        self.drawFrame(painter)
        margin = self.margin()
        rect = self.contentsRect()
        rect.adjust(margin, margin, -margin, -margin)
        text = self.text()
        width = rect.width()
        if text != self._text or width != self._width:
            self._text = text
            self._width = width
            self._elided = self.fontMetrics().elidedText(
                text, QtCore.Qt.ElideRight, width)
        option = QtGui.QStyleOption()
        option.initFrom(self)
        self.style().drawItemText(
            painter, rect, self.alignment(), option.palette,
            self.isEnabled(), self._elided, self.foregroundRole())

class MyMainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(QtGui.QMainWindow, self).__init__()

        self.setCentralWidget(QtGui.QLabel("main widget"))

        statusBar = QtGui.QStatusBar()
        self.setStatusBar(statusBar)

        statusBar.addWidget(ElidedLabel("first message"))
        statusBar.addWidget(ElidedLabel("second message"))
        statusBar.addWidget(ElidedLabel("a third long long long long long message"))

app = QtGui.QApplication(sys.argv)
window = MyMainWindow()
window.show()
sys.exit(app.exec_())