【问题标题】:How to insert a button inside a QLineEdit如何在 QLineEdit 中插入按钮
【发布时间】:2012-09-09 20:44:34
【问题描述】:

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

例如,像这张谷歌图片:

【问题讨论】:

    标签: pyqt4 qt4 pyside qlineedit qtoolbutton


    【解决方案1】:

    下面是来自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_())
    

    【讨论】:

    • 从 Qt 5.2 开始,QLineEdit.addAction() 是一种内置方式。此外,QLineEdit.setClearButtonEnabled() 在右侧添加了一个十字按钮(如在某些 OSX 控件上)以清除小部件的内容。
    • @Avaris 我已经根据我的需要调整了您的解决方案,但有一个小问题。当 QLineEdit 的内容太长时,它会与按钮重叠。通过将按钮的背景颜色设置为白色,我设法在一定程度上缓解了这个问题。这种方法的问题在于,部分内容消失在按钮后面。不能用光标或鼠标向右滚动以显示其余内容。我怎么解决这个问题?谢谢。
    【解决方案2】:

    感谢我们的同事,Avaris,但他的例子并没有说服我,我决定让另一个更容易和更少的代码。 去学习吧!

    #this code for example in btninlineedit.py
    
    from PyQt4.QtGui import *
    from PyQt4.QtCore import Qt
    from PyQt4 import QtCore, QtGui
    #Andrey Zhuk.
    #####
    try:
        _fromUtf8 = QtCore.QString.fromUtf8
    except AttributeError:
        _fromUtf8 = lambda s: s
    
    class ButtonInLineEdit(QLineEdit):
        def __init__(self,parent=None):
            QLineEdit.__init__(self,parent)
    
            self.ButtonShowKeyboard = QToolButton(self)
            self.ButtonShowKeyboard.setCursor(Qt.PointingHandCursor)
            #self.ButtonShowKeyboard.show()
            self.ButtonShowKeyboard.setFocusPolicy(Qt.NoFocus)
            self.ButtonShowKeyboard.setIcon(QtGui.QIcon("images/YourIcon.svg"))
            self.ButtonShowKeyboard.setStyleSheet("background: transparent; border: none;")
    
            layout = QHBoxLayout(self)
            layout.addWidget(self.ButtonShowKeyboard,0,Qt.AlignRight)
    
            layout.setSpacing(0)
            layout.setMargin(5)
            # ToolTip 
            self.ButtonShowKeyboard.setToolTip(QtGui.QApplication.translate("None", "Show virtual keyboard", None, QtGui.QApplication.UnicodeUTF8))
    
    
    #this code for example in main.py            
    class main(/////****///**/): 
        def __init__(self):
         #blablablablaaaa
    
            self.KeyboardShow = False
    
    self.connect(self.LineEdit.ButtonShowKeyboard, QtCore.SIGNAL("clicked()"), self.KeyboardShowHide)
    
    
    def KeyboardShowHide(self):
        try:
            if self.KeyboardShow:
                self.KeyboardShow = False
                self.WidgetKeyboard.hide()
            else:
                self.KeyboardShow = True
                self.WidgetKeyboard.show()
        except:
                debug ("ошибка при вызове функции скрытые или показа клавиатуры (Main Window)")
    #this code for example in btninlineedit.py
    
    from forms.btninlineedit import ButtonInLineEdit
    
    
    
            self.LineEdit = ButtonInLineEdit()
    

    【讨论】:

      【解决方案3】:

      这是可运行的代码:

      from PyQt4.QtGui import *
      from PyQt4.QtCore import *
      from sys import argv, exit
      
      class ButtonInLineEdit(QLineEdit):
          def __init__(self,parent=None):
              QLineEdit.__init__(self,parent)
      
              self.ButtonShowKeyboard = QToolButton(self)
              self.ButtonShowKeyboard.setCursor(Qt.PointingHandCursor)
      
              self.ButtonShowKeyboard.setFocusPolicy(Qt.NoFocus)
              self.ButtonShowKeyboard.setIcon(QIcon("icons/myIcon.png"))
              self.ButtonShowKeyboard.setStyleSheet("background: transparent; border: none;")
      
              layout = QHBoxLayout(self)
              layout.addWidget(self.ButtonShowKeyboard,0,Qt.AlignRight)
      
              layout.setSpacing(0)
              layout.setMargin(5)
      
              self.ButtonShowKeyboard.setToolTip(QApplication.translate("None", "Show virtual keyboard", None, QApplication.UnicodeUTF8))
      
      def MyFunction(arg=None):
          print "MyFunction() called: arg = %s"%arg
      
      a=QApplication(argv)
      LineEdit = ButtonInLineEdit()
      LineEdit.connect(LineEdit.ButtonShowKeyboard, SIGNAL("clicked()"), MyFunction)
      LineEdit.show()
      exit(a.exec_())
      

      【讨论】:

      • 嘿,我正在做类似的事情,但是我试图将这样的“按钮”附加到我在 Qt Designer 中创建的 UI 上。想知道是否可以使用您的解决方案来做到这一点?
      【解决方案4】:

      从 Qt 5.2 开始,QLineEdit.addAction() 是一种内置方法。 此外QLineEdit.setClearButtonEnabled() 在右侧添加了一个十字按钮(如在某些 OSX 控件上)以清除小部件的内容。

      【讨论】:

      • 你能举个例子吗?
      【解决方案5】:

      在qt C++中,我可以将pushButton拖放到LineEdit的左侧。之后,我只需要使用以下代码为LineEdit 设置styleSheet

      int FramWidth = lineEdit->style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
      
      lineEdit->setStyleSheet(QString("QLineEdit{padding-right: %1px; }").arg(ui->pushButton->sizeHint().width() + FramWidth +5));
      

      它对我有用。希望它可以提供帮助。

      【讨论】:

        【解决方案6】:
        class LineEditFileDialogWidget(QtWidgets.QLineEdit):
            def __init__(self, parent=None):
                super(LineEditFileDialogWidget, self).__init__(parent)
                self.setReadOnly(True)
        
                icon = QtWidgets.QApplication.style().standardIcon(QtWidgets.QStyle.SP_DirIcon)
                self.action = self.addAction(icon, QtWidgets.QLineEdit.TrailingPosition)
                self.action.triggered.connect(some function)
        

        这是一个将图标与 QLineEdit 一起使用的示例

        【讨论】:

          猜你喜欢
          • 2023-03-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-02-17
          • 1970-01-01
          • 1970-01-01
          • 2012-07-02
          相关资源
          最近更新 更多