本文整理匯總了Python中PyQt5.QtWidgets.QLineEdit.setFocus方法的典型用法代碼示例。如果您正苦於以下問題:Python QLineEdit.setFocus方法的具體用法?Python QLineEdit.setFocus怎麽用?Python QLineEdit.setFocus使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類PyQt5.QtWidgets.QLineEdit
的用法示例。
在下文中一共展示了QLineEdit.setFocus方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: AddLayerDialog
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setFocus [as 別名]
class AddLayerDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowModality(Qt.WindowModal)
self.setWindowTitle(self.tr("Add layer…"))
layout = QGridLayout(self)
layerNameLabel = QLabel(self.tr("Layer name:"), self)
self.layerNameEdit = QLineEdit(self)
self.layerNameEdit.setFocus(True)
self.layerColorVignette = ColorVignette(self)
self.layerColorVignette.setColor(LayerColorGenerator.getQColor())
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
l = 0
layout.addWidget(layerNameLabel, l, 0)
layout.addWidget(self.layerNameEdit, l, 1)
layout.addWidget(self.layerColorVignette, l, 2)
l += 1
layout.addWidget(buttonBox, l, 0, 1, 3)
self.setLayout(layout)
@classmethod
def getNewLayerNameAndColor(cls, parent):
dialog = cls(parent)
result = dialog.exec_()
name = dialog.layerNameEdit.text()
color = dialog.layerColorVignette.color()
if not result:
LayerColorGenerator.revert()
return (name, color.getRgbF(), result)
示例2: StatusBar
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setFocus [as 別名]
class StatusBar (QStatusBar):
def __init__(self):
super(StatusBar, self).__init__()
self.__statusMessageLabel = QLabel(self)
self.__statusDataLabel = QLabel(self)
self.__commandLine = QLineEdit(self)
self.addPermanentWidget(self.__statusMessageLabel, 1)
self.addPermanentWidget(self.__commandLine, 1)
self.addPermanentWidget(self.__statusDataLabel)
self.__commandLine.hide()
def setStatus(self, statusMessage, statusData, cursorPosition, cursorAnchor, eventFilter):
commandMode = cursorPosition != -1
self.__commandLine.setVisible(commandMode)
self.__statusMessageLabel.setVisible(not commandMode)
if commandMode:
self.__commandLine.installEventFilter(eventFilter)
self.__commandLine.setFocus()
self.__commandLine.setText(statusMessage)
self.__commandLine.setSelection(cursorPosition, cursorAnchor - cursorPosition)
else:
self.__statusMessageLabel.setText(statusMessage)
self.__statusDataLabel.setText(statusData)
示例3: AddLayerDialog
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setFocus [as 別名]
class AddLayerDialog(QDialog):
def __init__(self, parent=None):
super(AddLayerDialog, self).__init__(parent)
self.setWindowModality(Qt.WindowModal)
self.setWindowTitle(self.tr("Add layer…"))
layout = QGridLayout(self)
layerNameLabel = QLabel(self.tr("Layer name:"), self)
self.layerNameEdit = QLineEdit(self)
self.layerNameEdit.setFocus(True)
buttonBox = QDialogButtonBox(
QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
l = 0
layout.addWidget(layerNameLabel, l, 0)
layout.addWidget(self.layerNameEdit, l, 1)
l += 1
layout.addWidget(buttonBox, l, 0, 1, 2)
self.setLayout(layout)
@classmethod
def getNewLayerName(cls, parent):
dialog = cls(parent)
result = dialog.exec_()
name = dialog.layerNameEdit.text()
return (name, result)
示例4: RenameDialog
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setFocus [as 別名]
class RenameDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowModality(Qt.WindowModal)
self.setWindowTitle(self.tr("Rename…"))
nameLabel = QLabel(self.tr("Name:"), self)
self.nameEdit = QLineEdit(self)
self.nameEdit.setFocus(True)
buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
layout = QGridLayout(self)
l = 0
layout.addWidget(nameLabel, l, 0)
layout.addWidget(self.nameEdit, l, 1, 1, 3)
l += 1
layout.addWidget(buttonBox, l, 3)
self.setLayout(layout)
@classmethod
def getNewName(cls, parent, name=None):
dialog = cls(parent)
dialog.nameEdit.setText(name)
dialog.nameEdit.selectAll()
result = dialog.exec_()
name = dialog.nameEdit.text()
return (name, result)
示例5: Header
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setFocus [as 別名]
class Header(QHeaderView):
def __init__(self, orientation=Qt.Horizontal, parent=None):
super(Header, self).__init__(orientation, parent)
self.editable = True
self.setSectionsClickable(True)
self.setSectionResizeMode(QHeaderView.ResizeToContents)
self.line = QLineEdit(parent=self.viewport())
self.line.setAlignment(Qt.AlignTop)
self.line.setHidden(True)
self.line.blockSignals(True)
self.col = 0
# Connections
self.sectionDoubleClicked[int].connect(self.__edit)
self.line.editingFinished.connect(self.__done_editing)
def __edit(self, index):
if not self.editable:
return
geo = self.line.geometry()
geo.setWidth(self.sectionSize(index))
geo.moveLeft(self.sectionViewportPosition(index))
current_text = self.model().headerData(index, Qt.Horizontal,
Qt.DisplayRole)
self.line.setGeometry(geo)
self.line.setHidden(False)
self.line.blockSignals(False)
self.line.setText(str(current_text))
self.line.setFocus()
self.line.selectAll()
self.col = index
def __done_editing(self):
text = self.line.text()
if not text.strip():
# No debe ser vacío
QMessageBox.critical(self, "Error",
self.tr("El campo no debe ser vacío"))
self.line.hide()
return
self.line.blockSignals(True)
self.line.setHidden(False)
self.model().setHeaderData(self.col, Qt.Horizontal, text,
Qt.DisplayRole)
self.line.setText("")
self.line.hide()
self.setCurrentIndex(QModelIndex())
示例6: Login
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setFocus [as 別名]
class Login(QDialog):
def __init__(self, parent=None):
super(Login, self).__init__(parent)
usr = QLabel(u"用戶:")
pwd = QLabel(u"密碼:")
self.usrLineEdit = QLineEdit()
self.pwdLineEdit = QLineEdit()
self.pwdLineEdit.setEchoMode(QLineEdit.Password)
gridLayout = QGridLayout()
gridLayout.addWidget(usr, 0, 0, 1, 1)
gridLayout.addWidget(pwd, 1, 0, 1, 1)
gridLayout.addWidget(self.usrLineEdit, 0, 1, 1, 3);
gridLayout.addWidget(self.pwdLineEdit, 1, 1, 1, 3);
okBtn = QPushButton(u"確定")
cancelBtn = QPushButton(u"取消")
btnLayout = QHBoxLayout()
btnLayout.setSpacing(60)
btnLayout.addWidget(okBtn)
btnLayout.addWidget(cancelBtn)
dlgLayout = QVBoxLayout()
dlgLayout.setContentsMargins(40, 40, 40, 40)
dlgLayout.addLayout(gridLayout)
dlgLayout.addStretch(40)
dlgLayout.addLayout(btnLayout)
self.setLayout(dlgLayout)
okBtn.clicked.connect(self.accept)
cancelBtn.clicked.connect(self.reject)
self.setWindowTitle(u"登錄")
self.resize(300, 200)
def accept(self):
#year = strftime("%Y",localtime())
dt = datetime.now()
if self.usrLineEdit.text().strip() == "kerun" and self.pwdLineEdit.text() == "188102377":
super(Login, self).accept()
else:
QMessageBox.warning(self,
u"警告",
u"用戶名或密碼錯誤!",
QMessageBox.Yes)
self.usrLineEdit.setFocus()
示例7: AddAnchorDialog
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setFocus [as 別名]
class AddAnchorDialog(QDialog):
def __init__(self, pos=None, parent=None):
super(AddAnchorDialog, self).__init__(parent)
self.setWindowModality(Qt.WindowModal)
if pos is not None:
self.setWindowTitle(self.tr("Add anchor…"))
else:
self.setWindowTitle(self.tr("Rename anchor…"))
layout = QGridLayout(self)
anchorNameLabel = QLabel(self.tr("Anchor name:"), self)
self.anchorNameEdit = QLineEdit(self)
self.anchorNameEdit.setFocus(True)
if pos is not None:
anchorPositionLabel = QLabel(
self.tr("The anchor will be added at ({}, {}).")
.format(round(pos.x(), 2), round(pos.y(), 2)), self)
buttonBox = QDialogButtonBox(
QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
l = 0
layout.addWidget(anchorNameLabel, l, 0)
layout.addWidget(self.anchorNameEdit, l, 1, 1, 3)
if pos is not None:
l += 1
layout.addWidget(anchorPositionLabel, l, 0, 1, 4)
l += 1
layout.addWidget(buttonBox, l, 3)
self.setLayout(layout)
@classmethod
def getNewAnchorName(cls, parent, pos=None, name=None):
dialog = cls(pos, parent)
dialog.anchorNameEdit.setText(name)
result = dialog.exec_()
name = dialog.anchorNameEdit.text()
return (name, result)
示例8: AffixLineEdit
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setFocus [as 別名]
class AffixLineEdit(QWidget):
"""Single-line edit control with prefix/suffix text."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.prefix = QLabel()
self.suffix = QLabel()
self.edit = QLineEdit()
self.edit.setFrame(False)
self.setLayout(HBoxLayout([
self.prefix,
self.edit,
self.suffix,
], tight=True))
self.setAutoFillBackground(True)
def focusInEvent(self, event):
self.edit.setFocus()
event.accept()
示例9: Form
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setFocus [as 別名]
class Form(QDialog):
def __init__(self,parent=None):
super(Form,self).__init__(parent)
self.browser = QTextBrowser()
self.browser.setFont(QFont("Consolas",12,QFont.StyleItalic))
self.lineedit = QLineEdit('Type an express and press Enter')
self.lineedit.selectAll()
layout = QVBoxLayout()
layout.addWidget(self.browser)
layout.addWidget(self.lineedit)
self.setLayout(layout)
self.lineedit.setFocus()
# self.connect(self.lineedit,SIGNAL('returnPressed()'),self.updateUi)
self.lineedit.returnPressed.connect(self.updateUi)
self.setWindowTitle('Calculate')
def updateUi(self):
try:
text = self.lineedit.text()
self.browser.append('%s = %s' % (text, eval(text)))
except:
self.browser.append('%s is invalid!' % text)
示例10: InputWidget
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setFocus [as 別名]
class InputWidget(QFrame):
"""
Input contains QLabel and QLineEdit.
Represents single attribute in CalculableObject object.
Does not show private attributes that starts from '_'
"""
def __init__(self, parent, main_window, label_text):
super().__init__()
# if label_text.startswith('_'):
# return
self.label_text = label_text
self.input = QLineEdit()
main_window.communication.clean_items.connect(self.clean)
hbox = QHBoxLayout()
self.setLayout(hbox)
hbox.addWidget(QLabel(_(label_text)))
hbox.addStretch()
self.input.setAlignment(Qt.AlignRight)
# self.input.setFixedWidth(190)
self.input.textEdited.connect(functools.partial(parent.input_changed, label_text))
self.setGraphicsEffect(utils.get_shadow())
hbox.addWidget(self.input)
def set_value(self, value):
if value:
self.input.setText(str(value))
def clean(self):
self.input.setText('')
def mousePressEvent(self, event):
self.input.setFocus()
示例11: Header
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setFocus [as 別名]
class Header(QHeaderView):
def __init__(self, orientation=Qt.Horizontal, parent=None):
super(Header, self).__init__(orientation, parent)
self.setSectionsClickable(True)
self.setSectionResizeMode(QHeaderView.ResizeToContents)
self.line = QLineEdit(parent=self.viewport())
self.line.setAlignment(Qt.AlignTop)
self.line.setHidden(True)
self.line.blockSignals(True)
self.col = 0
# Connections
self.sectionDoubleClicked[int].connect(self.__edit)
self.line.editingFinished.connect(self.__done_editing)
def __edit(self, index):
geo = self.line.geometry()
geo.setWidth(self.sectionSize(index))
geo.moveLeft(self.sectionViewportPosition(index))
current_text = self.model().headerData(index, Qt.Horizontal)
self.line.setGeometry(geo)
self.line.setHidden(False)
self.line.blockSignals(False)
self.line.setText(str(current_text))
self.line.setFocus()
self.line.selectAll()
self.col = index
def __done_editing(self):
self.line.blockSignals(True)
self.line.setHidden(False)
text = self.line.text()
self.model().setHeaderData(self.col, Qt.Horizontal, text)
self.line.setText("")
self.line.hide()
self.setCurrentIndex(QModelIndex())
示例12: Form
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setFocus [as 別名]
class Form(QDialog) :
def __init__(self, parent=None) :
super(Form, self).__init__(parent)
self.function_edit = QLineEdit("x**2")
self.function_edit.selectAll()
self.parameter_edit = QLineEdit("np.linspace(0,1,4)")
self.parameter_edit.selectAll()
self.output_edit = QLineEdit(" ")
self.output_edit.selectAll()
self.plot = MatplotlibCanvas()
layout = QVBoxLayout()
layout.addWidget(self.plot)
layout.addWidget(self.function_edit)
layout.addWidget(self.parameter_edit)
layout.addWidget(self.output_edit)
self.setLayout(layout)
self.function_edit.setFocus()
self.output_edit.returnPressed.connect(self.updateUi)
self.setWindowTitle("Function Evaluator")
self.x = None
self.f = None
def updateUi(self) :
#try :
self.x = str(self.parameter_edit.text())
x = eval(self.x)
if len(x) > 1 :
x = np.array(x)
# Is there a cleaner way?
f = eval(str(self.function_edit.text()))
self.f = str(f)
self.f = self.f.replace("[","").replace("]","")
self.f = ",".join(self.f.split())
self.output_edit.setText(self.f)
self.plot.redraw(x, f)
示例13: Window
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setFocus [as 別名]
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
echoGroup = QGroupBox("Echo")
echoLabel = QLabel("Mode:")
echoComboBox = QComboBox()
echoComboBox.addItem("Normal")
echoComboBox.addItem("Password")
echoComboBox.addItem("PasswordEchoOnEdit")
echoComboBox.addItem("No Echo")
self.echoLineEdit = QLineEdit()
self.echoLineEdit.setFocus()
validatorGroup = QGroupBox("Validator")
validatorLabel = QLabel("Type:")
validatorComboBox = QComboBox()
validatorComboBox.addItem("No validator")
validatorComboBox.addItem("Integer validator")
validatorComboBox.addItem("Double validator")
self.validatorLineEdit = QLineEdit()
alignmentGroup = QGroupBox("Alignment")
alignmentLabel = QLabel("Type:")
alignmentComboBox = QComboBox()
alignmentComboBox.addItem("Left")
alignmentComboBox.addItem("Centered")
alignmentComboBox.addItem("Right")
self.alignmentLineEdit = QLineEdit()
inputMaskGroup = QGroupBox("Input mask")
inputMaskLabel = QLabel("Type:")
inputMaskComboBox = QComboBox()
inputMaskComboBox.addItem("No mask")
inputMaskComboBox.addItem("Phone number")
inputMaskComboBox.addItem("ISO date")
inputMaskComboBox.addItem("License key")
self.inputMaskLineEdit = QLineEdit()
accessGroup = QGroupBox("Access")
accessLabel = QLabel("Read-only:")
accessComboBox = QComboBox()
accessComboBox.addItem("False")
accessComboBox.addItem("True")
self.accessLineEdit = QLineEdit()
echoComboBox.activated.connect(self.echoChanged)
validatorComboBox.activated.connect(self.validatorChanged)
alignmentComboBox.activated.connect(self.alignmentChanged)
inputMaskComboBox.activated.connect(self.inputMaskChanged)
accessComboBox.activated.connect(self.accessChanged)
echoLayout = QGridLayout()
echoLayout.addWidget(echoLabel, 0, 0)
echoLayout.addWidget(echoComboBox, 0, 1)
echoLayout.addWidget(self.echoLineEdit, 1, 0, 1, 2)
echoGroup.setLayout(echoLayout)
validatorLayout = QGridLayout()
validatorLayout.addWidget(validatorLabel, 0, 0)
validatorLayout.addWidget(validatorComboBox, 0, 1)
validatorLayout.addWidget(self.validatorLineEdit, 1, 0, 1, 2)
validatorGroup.setLayout(validatorLayout)
alignmentLayout = QGridLayout()
alignmentLayout.addWidget(alignmentLabel, 0, 0)
alignmentLayout.addWidget(alignmentComboBox, 0, 1)
alignmentLayout.addWidget(self.alignmentLineEdit, 1, 0, 1, 2)
alignmentGroup. setLayout(alignmentLayout)
inputMaskLayout = QGridLayout()
inputMaskLayout.addWidget(inputMaskLabel, 0, 0)
inputMaskLayout.addWidget(inputMaskComboBox, 0, 1)
inputMaskLayout.addWidget(self.inputMaskLineEdit, 1, 0, 1, 2)
inputMaskGroup.setLayout(inputMaskLayout)
accessLayout = QGridLayout()
accessLayout.addWidget(accessLabel, 0, 0)
accessLayout.addWidget(accessComboBox, 0, 1)
accessLayout.addWidget(self.accessLineEdit, 1, 0, 1, 2)
accessGroup.setLayout(accessLayout)
layout = QGridLayout()
layout.addWidget(echoGroup, 0, 0)
layout.addWidget(validatorGroup, 1, 0)
layout.addWidget(alignmentGroup, 2, 0)
layout.addWidget(inputMaskGroup, 0, 1)
layout.addWidget(accessGroup, 1, 1)
self.setLayout(layout)
#.........這裏部分代碼省略.........
示例14: Client
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setFocus [as 別名]
class Client(QDialog):
def __init__(self, parent=None):
super(Client, self).__init__(parent)
self.networkSession = None
self.blockSize = 0
self.currentFortune = ""
hostLabel = QLabel("&Server name:")
portLabel = QLabel("S&erver port:")
self.hostCombo = QComboBox()
self.hostCombo.setEditable(True)
name = QHostInfo.localHostName()
if name != "":
self.hostCombo.addItem(name)
domain = QHostInfo.localDomainName()
if domain != "":
self.hostCombo.addItem(name + "." + domain)
if name != "localhost":
self.hostCombo.addItem("localhost")
ipAddressesList = QNetworkInterface.allAddresses()
for ipAddress in ipAddressesList:
if not ipAddress.isLoopback():
self.hostCombo.addItem(ipAddress.toString())
for ipAddress in ipAddressesList:
if ipAddress.isLoopback():
self.hostCombo.addItem(ipAddress.toString())
self.portLineEdit = QLineEdit()
self.portLineEdit.setValidator(QIntValidator(1, 65535, self))
hostLabel.setBuddy(self.hostCombo)
portLabel.setBuddy(self.portLineEdit)
self.statusLabel = QLabel("This examples requires that you run " "the Fortune Server example as well.")
self.getFortuneButton = QPushButton("Get Fortune")
self.getFortuneButton.setDefault(True)
self.getFortuneButton.setEnabled(False)
quitButton = QPushButton("Quit")
buttonBox = QDialogButtonBox()
buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole)
buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole)
self.tcpSocket = QTcpSocket(self)
self.hostCombo.editTextChanged.connect(self.enableGetFortuneButton)
self.portLineEdit.textChanged.connect(self.enableGetFortuneButton)
self.getFortuneButton.clicked.connect(self.requestNewFortune)
quitButton.clicked.connect(self.close)
self.tcpSocket.readyRead.connect(self.readFortune)
self.tcpSocket.error.connect(self.displayError)
mainLayout = QGridLayout()
mainLayout.addWidget(hostLabel, 0, 0)
mainLayout.addWidget(self.hostCombo, 0, 1)
mainLayout.addWidget(portLabel, 1, 0)
mainLayout.addWidget(self.portLineEdit, 1, 1)
mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2)
mainLayout.addWidget(buttonBox, 3, 0, 1, 2)
self.setLayout(mainLayout)
self.setWindowTitle("Fortune Client")
self.portLineEdit.setFocus()
manager = QNetworkConfigurationManager()
if manager.capabilities() & QNetworkConfigurationManager.NetworkSessionRequired:
settings = QSettings(QSettings.UserScope, "QtProject")
settings.beginGroup("QtNetwork")
id = settings.value("DefaultNetworkConfiguration")
settings.endGroup()
config = manager.configurationFromIdentifier(id)
if config.state() & QNetworkConfiguration.Discovered == 0:
config = manager.defaultConfiguration()
self.networkSession = QNetworkSession(config, self)
self.networkSession.opened.connect(self.sessionOpened)
self.getFortuneButton.setEnabled(False)
self.statusLabel.setText("Opening network session.")
self.networkSession.open()
def requestNewFortune(self):
self.getFortuneButton.setEnabled(False)
self.blockSize = 0
self.tcpSocket.abort()
self.tcpSocket.connectToHost(self.hostCombo.currentText(), int(self.portLineEdit.text()))
def readFortune(self):
instr = QDataStream(self.tcpSocket)
#.........這裏部分代碼省略.........
示例15: AddressBook
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setFocus [as 別名]
class AddressBook(QWidget):
def __init__(self, parent=None):
super(AddressBook, self).__init__(parent)
self.contacts = SortedDict()
self.oldName = ''
self.oldAddress = ''
nameLabel = QLabel("Name:")
self.nameLine = QLineEdit()
self.nameLine.setReadOnly(True)
addressLabel = QLabel("Address:")
self.addressText = QTextEdit()
self.addressText.setReadOnly(True)
self.addButton = QPushButton("&Add")
self.addButton.show()
self.submitButton = QPushButton("&Submit")
self.submitButton.hide()
self.cancelButton = QPushButton("&Cancel")
self.cancelButton.hide()
self.addButton.clicked.connect(self.addContact)
self.submitButton.clicked.connect(self.submitContact)
self.cancelButton.clicked.connect(self.cancel)
buttonLayout1 = QVBoxLayout()
buttonLayout1.addWidget(self.addButton, Qt.AlignTop)
buttonLayout1.addWidget(self.submitButton)
buttonLayout1.addWidget(self.cancelButton)
buttonLayout1.addStretch()
mainLayout = QGridLayout()
mainLayout.addWidget(nameLabel, 0, 0)
mainLayout.addWidget(self.nameLine, 0, 1)
mainLayout.addWidget(addressLabel, 1, 0, Qt.AlignTop)
mainLayout.addWidget(self.addressText, 1, 1)
mainLayout.addLayout(buttonLayout1, 1, 2)
self.setLayout(mainLayout)
self.setWindowTitle("Simple Address Book")
def addContact(self):
self.oldName = self.nameLine.text()
self.oldAddress = self.addressText.toPlainText()
self.nameLine.clear()
self.addressText.clear()
self.nameLine.setReadOnly(False)
self.nameLine.setFocus(Qt.OtherFocusReason)
self.addressText.setReadOnly(False)
self.addButton.setEnabled(False)
self.submitButton.show()
self.cancelButton.show()
def submitContact(self):
name = self.nameLine.text()
address = self.addressText.toPlainText()
if name == "" or address == "":
QMessageBox.information(self, "Empty Field",
"Please enter a name and address.")
return
if name not in self.contacts:
self.contacts[name] = address
QMessageBox.information(self, "Add Successful",
"\"%s\" has been added to your address book." % name)
else:
QMessageBox.information(self, "Add Unsuccessful",
"Sorry, \"%s\" is already in your address book." % name)
return
if not self.contacts:
self.nameLine.clear()
self.addressText.clear()
self.nameLine.setReadOnly(True)
self.addressText.setReadOnly(True)
self.addButton.setEnabled(True)
self.submitButton.hide()
self.cancelButton.hide()
def cancel(self):
self.nameLine.setText(self.oldName)
self.nameLine.setReadOnly(True)
self.addressText.setText(self.oldAddress)
self.addressText.setReadOnly(True)
self.addButton.setEnabled(True)
self.submitButton.hide()
self.cancelButton.hide()