PyQt4:QLabel带清除按钮

2024-09-30 12:23:51 发布

您现在位置:Python中文网/ 问答频道 /正文

首先我要展示代码。在

class XLineEdit(QtGui.QLineEdit):
  '''QLineEdit with clear button, which appears when user enters text.'''
  def __init__(self, pixmap, parent=None):
    QtGui.QLineEdit.__init__(self, parent)
    self.layout = QtGui.QHBoxLayout(self)
    self.image = QtGui.QLabel(self)
    self.image.setCursor(QtCore.Qt.ArrowCursor)
    self.image.setFocusPolicy(QtCore.Qt.NoFocus)
    self.image.setStyleSheet("border: none;")
    self.image.setPixmap(pixmap)
    self.image.setSizePolicy(
      QtGui.QSizePolicy.Expanding,
      QtGui.QSizePolicy.Expanding)
    self.image.adjustSize()
    self.image.setScaledContents(True)
    self.layout.addWidget(
      self.image, alignment=QtCore.Qt.AlignRight)
    self.textChanged.connect(self.changed)
    self.image.hide()

  def changed(self, text):
    if len(text) > 0:
      self.image.show()
    else: # if entry is empty
      self.image.hide()

它从QLineEdit右侧的QLabel创建带有自定义按钮的QLineEdit对象。我只有两个问题:

  1. 如果我改变XLineEdit(“XLineEdit object.setFont(QFont)),图像按钮在垂直方向看起来不错,但在水平方向看起来很难看。垂直大小似乎随着QLineEdit字体大小的改变而改变,但水平大小不会改变。我该怎么解决这个问题?有没有其他方法可以用clear按钮创建QLineEdit?我尝试用自定义的QIcon创建QPushButton,但是图标根本没有改变它的大小(既不是垂直的,也不是水平的)。

  2. 当用户单击QLabel时,如何创建新的信号?似乎QPushButton的“clicked”没有类似的功能。

谢谢!在


Tags: textimageselfinitdef水平qt按钮
1条回答
网友
1楼 · 发布于 2024-09-30 12:23:51
当您在ReCuteDeV中使用了一个C++按钮的链接来注释您的问题时,我想添加关于您的第二个问题的信息…在

通过重载MousePressEvent并发出自己的自定义信号,可以创建一个可单击的QLabel。在

从PyQt4.QtCore导入pyqtSignal 从PyQt4.QtGui导入QLabel,QStyle

class ClickLabel(QLabel):

    clicked = pyqtSignal()

    def __init__(self, *args, **kwargs)
        super(ClickLabel, self).__init__(*args, **kwargs)

    def mousePressEvent(self, event):
        event.accept()
        self.clicked.emit()

关于其他注释中提供的C++链接的注释。他们没有使用HBoxLayout,而是直接将按钮作为QLabel小部件的子元素,并使用resizeEvent将其始终移动到QLabel的右侧。在

相关问题 更多 >

    热门问题