【发布时间】:2012-02-06 02:20:04
【问题描述】:
首先我会展示代码。
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 对象。我只有两个问题:
如果我更改 XLineEdit 的字体 ("XLineEdit object".setFont(QFont)),图像按钮在垂直方向看起来不错,但在水平方向看起来很难看。改变 QLineEdit 字体的大小似乎会改变垂直大小,但水平大小不会。我怎样才能解决这个问题?有没有其他方法可以使用清除按钮创建 QLineEdit?我尝试使用自定义 QIcon 创建 QPushButton,但图标根本不会改变它的大小(既不是垂直的,也不是水平的)。
当用户点击 QLabel 时如何创建新信号? QPushButton 的 'clicked' 好像没有类比。
谢谢!
【问题讨论】:
-
您是否尝试过使用 QToolButton 来制作您希望可点击的图像? doc.qt.nokia.com/4.7-snapshot/qtoolbutton.html
-
看看这个例子Lineedit with a clear button。但它是用 C++ 编写的。
-
@gfortune:谢谢,我试试看。
-
@reclosedev:我不会说 C++ 很好,但是这个例子是微不足道的,我想我已经理解了。谢谢,看来我找到了我要找的东西。