pyqt4 - 如何在 QLineEdit 中插入按钮

标签 pyqt4 qt4 pyside qlineedit qtoolbutton

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

例如,像这个谷歌图片:

Button in line edit

最佳答案

以下是来自 here 的 Qt 代码的几乎直接翻译。 .

区别:

  • 按钮始终可见
  • 单击按钮发出 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_())
    

    关于pyqt4 - 如何在 QLineEdit 中插入按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12462562/

    相关文章:

    pyqt4 - PyQt5 或 Pyqt4,我应该升级吗?

    python - Qt : How to render 3D animation shapes over a camera video stream?

    c++ - 在 QPlainTextEdit 中获取指向 QTextBlock 的指针

    python - `pip install pyside` 在 Linux 上卡住?

    c++ - QML textInput 元素中的自动完成和建议

    qt - 不同的 QMessageBox.Roles 是什么意思?

    python - 如何修复 Qtab 并在选项卡区域创建更多按钮和文本行

    PyQt4:QSpinBox 不接受高于 100 的值

    python - PyQT - 列出 QWidgets/Windows

    c++ - Qt 应用程序 : Simulating modal behaviour (enable/disable user input)