【问题标题】:LineEdit box in PyQt5PyQt5 中的 LineEdit 框
【发布时间】:2019-04-13 14:33:40
【问题描述】:

当我在 lineEdit 框中按 Enter 键时,会执行函数 enter_LineEdit() 和函数 click_Edit()。为什么它执行函数click_Edit()?不能!

我希望有人向我解释为什么它会这样工作?

#!/usr/bin/python3.6
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import QMainWindow,QApplication,QPushButton,QDialog,QHBoxLayout,QLabel,QWidget,QLineEdit
from PyQt5 import QtGui
from PyQt5 import QtCore


class Window(QMainWindow):

    def __init__(self):
        super().__init__()
        self.setGeometry(100,100,600,400)
        self.CreateBtn()
        self.show()

    def CreateBtn(self):
        button = QPushButton("Second Window", self)
        button.setGeometry(QtCore.QRect(30,100,200,80))
        button.setIconSize(QtCore.QSize(70,70))
        button.clicked.connect(self.SecWin)

    def SecWin(self):
        self.d = SecondWindow()
        self.d.Create_SecWin()
        self.d.Create_Object()
        self.d.Create_Layout()


class SecondWindow(QDialog):

    def Create_SecWin(self):
        self.setGeometry(600,360,400,100)
        self.show()

    def Create_Object(self):
        self.btnEdit = QPushButton("Edit",self)
        self.btnEdit.clicked.connect(self.click_Edit)
        self.labelSearch = QLabel("Search:",self)
        self.lineEdit = QLineEdit(self)
        self.lineEdit.returnPressed.connect(self.enter_LineEdit)

    def Create_Layout(self):
        hbox1 = QHBoxLayout()
        hbox1.addWidget(self.btnEdit)
        hbox1.addWidget(self.labelSearch)
        hbox1.addWidget(self.lineEdit)
        self.setLayout(hbox1)

    def click_Edit(self):
        print("Philip")

    def enter_LineEdit(self):
        print("Karl")



App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec_())

【问题讨论】:

    标签: python python-3.x pyqt pyqt5 qlineedit


    【解决方案1】:

    如果您查看 QPushButton 的 autoDefault 属性的文档:

    此属性保存按钮是否为自动默认按钮

    如果此属性设置为 true,则按钮为自动 默认按钮。

    在某些 GUI 样式中,默认按钮是用额外的框架绘制的 周围,​​最多 3 个像素或更多。 Qt 自动保留这个空间 围绕自动默认按钮免费,即,自动默认按钮可能有 尺寸稍大的提示。

    对于有 QDialog 的按钮,此属性的默认值为 true 父母;否则默认为 false。

    有关默认和自动默认的详细信息,请参阅默认属性 互动。

    也来自default 属性:

    [...]

    此属性设置为 true 的按钮(即对话框的默认设置) 按钮,)将在用户按下回车时自动按下, 有一个例外:如果自动默认按钮当前具有焦点,则 按下自动默认按钮。 当对话框有自动默认按钮时 但没有默认按钮,按 enter 将按 当前具有焦点的自动默认按钮,或者如果没有按钮具有 焦点,焦点链中的下一个自动默认按钮

    [...]

    即在QDialog中按下回车键时会按下部分QPushButton,因为所有QPushButton的autoDefault属性都为True,所以解决方法是设置为False:

    self.btnEdit = QPushButton("Edit", self)
    self.btnEdit.setAutoDefault(False)
    

    【讨论】:

    • 感谢 eyllanesc,它完美地解决了我的问题。我无法理解这个“自动默认”,但也没关系。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多