如何在 QLineEdit 中插入按钮 [英] How to insert a button inside a QLineEdit

查看:147
本文介绍了如何在 QLineEdit 中插入按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助在可以调用函数的 QLineEdit 中插入一个按钮.

I need help inserting a button inside in a QLineEdit that can call a function.

例如,像这个谷歌图片:

For example, like this google image:

推荐答案

下面是从 此处.

区别:

  • 按钮始终可见
  • 点击按钮发出buttonClicked(bool)信号

代码:

from PyQt4 import QtGui, QtCore

class ButtonLineEdit(QtGui.QLineEdit):
    buttonClicked = QtCore.pyqtSignal(bool)

    def __init__(self, icon_file, parent=None):
        super(ButtonLineEdit, self).__init__(parent)

        self.button = QtGui.QToolButton(self)
        self.button.setIcon(QtGui.QIcon(icon_file))
        self.button.setStyleSheet('border: 0px; padding: 0px;')
        self.button.setCursor(QtCore.Qt.ArrowCursor)
        self.button.clicked.connect(self.buttonClicked.emit)

        frameWidth = self.style().pixelMetric(QtGui.QStyle.PM_DefaultFrameWidth)
        buttonSize = self.button.sizeHint()

        self.setStyleSheet('QLineEdit {padding-right: %dpx; }' % (buttonSize.width() + frameWidth + 1))
        self.setMinimumSize(max(self.minimumSizeHint().width(), buttonSize.width() + frameWidth*2 + 2),
                            max(self.minimumSizeHint().height(), buttonSize.height() + frameWidth*2 + 2))

    def resizeEvent(self, event):
        buttonSize = self.button.sizeHint()
        frameWidth = self.style().pixelMetric(QtGui.QStyle.PM_DefaultFrameWidth)
        self.button.move(self.rect().right() - frameWidth - buttonSize.width(),
                         (self.rect().bottom() - buttonSize.height() + 1)/2)
        super(ButtonLineEdit, self).resizeEvent(event)

用法:

import sys
from PyQt4 import QtGui

def buttonClicked():
    print 'You clicked the button!'

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = ButtonLineEdit('/path/to/my_fancy_icon.png')
    main.buttonClicked.connect(buttonClicked)
    main.show()

    sys.exit(app.exec_())

这篇关于如何在 QLineEdit 中插入按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆