PyQt5中的LineEdit框

问题描述 投票:1回答:1

当我在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个回答
0
投票

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

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

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

在某些GUI样式中,绘制一个默认按钮,其周围有一个额外的框架,最多3个像素或更多。 Qt自动保持此空间在自动默认按钮周围空闲,即,自动默认按钮可能具有稍大的提示。

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

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

还有来自default的财产:

[...]

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

[...]

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

self.btnEdit = QPushButton("Edit", self)
self.btnEdit.setAutoDefault(False)
© www.soinside.com 2019 - 2024. All rights reserved.