PyQt5 中的 LineEdit 框

LineEdit box in PyQt5

当我在 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_())

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

This property holds whether the push button is an auto default button

If this property is set to true then the push button is an auto default button.

In some GUI styles a default button is drawn with an extra frame around it, up to 3 pixels or more. Qt automatically keeps this space free around auto-default buttons, i.e., auto-default buttons may have a slightly larger size hint.

This property's default is true for buttons that have a QDialog parent; otherwise it defaults to false.

See the default property for details of how default and auto-default interact.

还有来自 default 属性:

[...]

A button with this property set to true (i.e., the dialog's default button,) will automatically be pressed when the user presses enter, with one exception: if an autoDefault button currently has focus, the autoDefault button is pressed. When the dialog has autoDefault buttons but no default button, pressing enter will press either the autoDefault button that currently has focus, or if no button has focus, the next autoDefault button in the focus chain.

[...]

也就是说,在QDialog中按下回车键时,某些QPushButtons会被按下,因为所有QPushButtons都有autoDefault 属性为True,所以解决方法是将其设置为False:

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