本文整理匯總了Python中PyQt5.QtWidgets.QLineEdit.setPalette方法的典型用法代碼示例。如果您正苦於以下問題:Python QLineEdit.setPalette方法的具體用法?Python QLineEdit.setPalette怎麽用?Python QLineEdit.setPalette使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類PyQt5.QtWidgets.QLineEdit
的用法示例。
在下文中一共展示了QLineEdit.setPalette方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: GestionEleve
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setPalette [as 別名]
class GestionEleve(QWidget):
def __init__(self,parent=None):
super(GestionEleve,self).__init__(parent)
#charge la classe en cour
self.initClass()
palette = QPalette()
palette.setColor(QPalette.Text,QColor(128,128,128))
self.leNom = QLineEdit(self)
self.leNom.setText("NOM..")
self.leNom.setPalette(palette)
self.lePrenom = QLineEdit(self)
self.lePrenom.setText("PRENOM..")
self.lePrenom.setPalette(palette)
self.comboSex = QComboBox(self)
self.comboSex.addItem("sexe..")
self.comboSex.addItem("M")
self.comboSex.addItem("F")
self.comboClasse = self.initComboClasse(["CE1","CE2"])
self.buttonSave = QPushButton("Save")
self.buttonSave.clicked.connect(self.saveEleve)
layout = QHBoxLayout()
layout.addStretch()
layout.addWidget(self.leNom)
layout.addWidget(self.lePrenom)
layout.addWidget(self.comboSex)
layout.addWidget(self.comboClasse)
layout.addWidget(self.buttonSave)
layout.addStretch()
self.setLayout(layout)
def initComboClasse(self,list):
res = QComboBox()
res.addItem("classe..")
for elt in list:
res.addItem(elt)
return res
def saveEleve(self):
if (self.leNom.text == "NOM.."
or self.lePrenom.text == "PRENOM.."
or str(self.comboSex.currentText()) == "sexe.."
or str(self.comboClasse.currentText()) == "classe.."
):
pass
#on enregistre pas
else :
pass
#on enregistre
def initClass(self):
pass
示例2: PathChoice
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setPalette [as 別名]
class PathChoice(ChoiceWidget):
def __init__( self, criterion, title, explainer ) :
super().__init__( title, explainer )
self.criterion = criterion
self.path_edit = QLineEdit()
self.path_valid = True
self.path_edit.textChanged.connect( self.path_working )
self.path_edit.editingFinished.connect( self.check_path )
self.browse_button = QPushButton(
_TR('Path preference button', 'Browse' ) )
self.browse_button.clicked.connect( self.browse )
self.layout().addWidget( self.path_edit, 1 )
self.layout().addWidget( self.browse_button, 0 )
# Change the color of the background of the path_edit.
def set_path_color( self, color_name ) :
p = self.path_edit.palette()
p.setColor( QPalette.Normal, QPalette.Base, QColor( color_name ) )
self.path_edit.setPalette(p)
# User is editing the path string. If it is now marked invalid,
# clear that and make its background white again.
def path_working( self ) :
if self.path_valid : return
self.path_valid = True
self.set_path_color('White')
# Return pressed or focus-out of the path line-edit. Check for
# validity per the criterion.
def check_path( self ) :
if os.access( self.path_edit.text(), self.criterion ) :
return
if self.path_edit.text() : # is not null
utilities.beep()
self.path_valid = False
self.set_path_color( 'Pink' )
# User wants to browse for a path. The subclass must implement
# this by calling a utilities dialog with a specific caption.
def browse(self) :
pass
示例3: ReTextWindow
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setPalette [as 別名]
#.........這裏部分代碼省略.........
self.enableSpellCheck(self.actionEnableSC.isChecked())
if setdefault:
globalSettings.spellCheckLocale = sl
def searchBarVisibilityChanged(self, visible):
self.actionSearch.setChecked(visible)
if visible:
self.searchEdit.setFocus(Qt.ShortcutFocusReason)
def find(self, back=False):
flags = QTextDocument.FindFlags()
if back:
flags |= QTextDocument.FindBackward
if self.csBox.isChecked():
flags |= QTextDocument.FindCaseSensitively
text = self.searchEdit.text()
editBox = self.currentTab.editBox
cursor = editBox.textCursor()
newCursor = editBox.document().find(text, cursor, flags)
if not newCursor.isNull():
editBox.setTextCursor(newCursor)
return self.setSearchEditColor(True)
cursor.movePosition(QTextCursor.End if back else QTextCursor.Start)
newCursor = editBox.document().find(text, cursor, flags)
if not newCursor.isNull():
editBox.setTextCursor(newCursor)
return self.setSearchEditColor(True)
self.setSearchEditColor(False)
def setSearchEditColor(self, found):
palette = self.searchEdit.palette()
palette.setColor(QPalette.Active, QPalette.Base,
Qt.white if found else QColor(255, 102, 102))
self.searchEdit.setPalette(palette)
def showInDir(self):
if self.currentTab.fileName:
path = QFileInfo(self.currentTab.fileName).path()
QDesktopServices.openUrl(QUrl.fromLocalFile(path))
else:
QMessageBox.warning(self, '', self.tr("Please, save the file somewhere."))
def setCurrentFile(self):
self.setWindowTitle("")
self.tabWidget.setTabText(self.ind, self.currentTab.getDocumentTitle(baseName=True))
self.tabWidget.setTabToolTip(self.ind, self.currentTab.fileName or '')
self.setWindowFilePath(self.currentTab.fileName)
files = readListFromSettings("recentFileList")
while self.currentTab.fileName in files:
files.remove(self.currentTab.fileName)
files.insert(0, self.currentTab.fileName)
if len(files) > 10:
del files[10:]
writeListToSettings("recentFileList", files)
QDir.setCurrent(QFileInfo(self.currentTab.fileName).dir().path())
self.docTypeChanged()
def createNew(self, text=None):
self.createTab("")
self.ind = self.tabWidget.count()-1
self.tabWidget.setCurrentIndex(self.ind)
if text:
self.currentTab.editBox.textCursor().insertText(text)
def switchTab(self, shift=1):
self.tabWidget.setCurrentIndex((self.ind + shift) % self.tabWidget.count())
示例4: Search
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setPalette [as 別名]
class Search(plugin.MainWindowPlugin, QWidget):
def __init__(self, mainwindow):
QWidget.__init__(self, mainwindow)
self._currentView = None
self._positions = []
self._positionsDirty = True
self._replace = False # are we in replace mode?
self._going = False # are we moving the text cursor?
mainwindow.currentViewChanged.connect(self.viewChanged)
mainwindow.actionCollection.edit_find_next.triggered.connect(self.findNext)
mainwindow.actionCollection.edit_find_previous.triggered.connect(self.findPrevious)
# don't inherit looks from view
self.setFont(QApplication.font())
self.setPalette(QApplication.palette())
grid = QGridLayout(spacing=2)
grid.setContentsMargins(4, 0, 4, 0)
grid.setVerticalSpacing(0)
self.setLayout(grid)
self.searchEntry = QLineEdit(textChanged=self.slotSearchChanged)
self.searchLabel = QLabel()
self.prevButton = QToolButton(autoRaise=True, focusPolicy=Qt.NoFocus, clicked=self.findPrevious)
self.prevButton.setIcon(icons.get('go-previous'))
self.nextButton = QToolButton(autoRaise=True, focusPolicy=Qt.NoFocus, clicked=self.findNext)
self.nextButton.setIcon(icons.get('go-next'))
self.caseCheck = QCheckBox(checked=True, focusPolicy=Qt.NoFocus)
self.regexCheck = QCheckBox(focusPolicy=Qt.NoFocus)
self.countLabel = QLabel(alignment=Qt.AlignRight | Qt.AlignVCenter)
self.countLabel.setMinimumWidth(QApplication.fontMetrics().width("9999"))
self.closeButton = QToolButton(autoRaise=True, focusPolicy=Qt.NoFocus)
self.hideAction = QAction(self, triggered=self.slotHide)
self.hideAction.setShortcut(QKeySequence(Qt.Key_Escape))
self.hideAction.setIcon(self.style().standardIcon(QStyle.SP_DialogCloseButton))
self.closeButton.setDefaultAction(self.hideAction)
grid.addWidget(self.searchLabel, 0, 0)
grid.addWidget(self.searchEntry, 0, 1)
grid.addWidget(self.prevButton, 0, 2)
grid.addWidget(self.nextButton, 0, 3)
grid.addWidget(self.caseCheck, 0, 4)
grid.addWidget(self.regexCheck, 0, 5)
grid.addWidget(self.countLabel, 0, 6)
grid.addWidget(self.closeButton, 0, 7)
self.caseCheck.toggled.connect(self.slotSearchChanged)
self.regexCheck.toggled.connect(self.slotSearchChanged)
self.replaceEntry = QLineEdit()
self.replaceLabel = QLabel()
self.replaceButton = QPushButton(clicked=self.slotReplace)
self.replaceAllButton = QPushButton(clicked=self.slotReplaceAll)
grid.addWidget(self.replaceLabel, 1, 0)
grid.addWidget(self.replaceEntry, 1, 1)
grid.addWidget(self.replaceButton, 1, 4)
grid.addWidget(self.replaceAllButton, 1, 5)
app.settingsChanged.connect(self.readSettings)
self.readSettings()
app.translateUI(self)
def translateUI(self):
self.searchLabel.setText(_("Search:"))
self.prevButton.setToolTip(_("Find Previous"))
self.nextButton.setToolTip(_("Find Next"))
self.caseCheck.setText(_("&Case"))
self.caseCheck.setToolTip(_("Case Sensitive"))
self.regexCheck.setText(_("&Regex"))
self.regexCheck.setToolTip(_("Regular Expression"))
self.countLabel.setToolTip(_("The total number of matches"))
self.hideAction.setToolTip(_("Close"))
self.replaceLabel.setText(_("Replace:"))
self.replaceButton.setText(_("Re&place"))
self.replaceButton.setToolTip(_("Replaces the next occurrence of the search term."))
self.replaceAllButton.setText(_("&All"))
self.replaceAllButton.setToolTip(_("Replaces all occurrences of the search term in the document or selection."))
def readSettings(self):
data = textformats.formatData('editor')
self.searchEntry.setFont(data.font)
self.replaceEntry.setFont(data.font)
p = data.palette()
self.searchEntry.setPalette(p)
self.replaceEntry.setPalette(p)
def currentView(self):
"""Return the currently active View."""
return self._currentView and self._currentView()
def setCurrentView(self, view):
"""Set the currently active View, called by showWidget()."""
cur = self.currentView()
if cur:
cur.selectionChanged.disconnect(self.slotSelectionChanged)
cur.document().contentsChanged.disconnect(self.slotDocumentContentsChanged)
if view:
view.selectionChanged.connect(self.slotSelectionChanged)
#.........這裏部分代碼省略.........
示例5: RegExpDialog
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setPalette [as 別名]
class RegExpDialog(QDialog):
MaxCaptures = 6
def __init__(self, parent=None):
super(RegExpDialog, self).__init__(parent)
self.patternComboBox = QComboBox()
self.patternComboBox.setEditable(True)
self.patternComboBox.setSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Preferred)
patternLabel = QLabel("&Pattern:")
patternLabel.setBuddy(self.patternComboBox)
self.escapedPatternLineEdit = QLineEdit()
self.escapedPatternLineEdit.setReadOnly(True)
palette = self.escapedPatternLineEdit.palette()
palette.setBrush(QPalette.Base,
palette.brush(QPalette.Disabled, QPalette.Base))
self.escapedPatternLineEdit.setPalette(palette)
escapedPatternLabel = QLabel("&Escaped Pattern:")
escapedPatternLabel.setBuddy(self.escapedPatternLineEdit)
self.syntaxComboBox = QComboBox()
self.syntaxComboBox.addItem("Regular expression v1", QRegExp.RegExp)
self.syntaxComboBox.addItem("Regular expression v2", QRegExp.RegExp2)
self.syntaxComboBox.addItem("Wildcard", QRegExp.Wildcard)
self.syntaxComboBox.addItem("Fixed string", QRegExp.FixedString)
syntaxLabel = QLabel("&Pattern Syntax:")
syntaxLabel.setBuddy(self.syntaxComboBox)
self.textComboBox = QComboBox()
self.textComboBox.setEditable(True)
self.textComboBox.setSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Preferred)
textLabel = QLabel("&Text:")
textLabel.setBuddy(self.textComboBox)
self.caseSensitiveCheckBox = QCheckBox("Case &Sensitive")
self.caseSensitiveCheckBox.setChecked(True)
self.minimalCheckBox = QCheckBox("&Minimal")
indexLabel = QLabel("Index of Match:")
self.indexEdit = QLineEdit()
self.indexEdit.setReadOnly(True)
matchedLengthLabel = QLabel("Matched Length:")
self.matchedLengthEdit = QLineEdit()
self.matchedLengthEdit.setReadOnly(True)
self.captureLabels = []
self.captureEdits = []
for i in range(self.MaxCaptures):
self.captureLabels.append(QLabel("Capture %d:" % i))
self.captureEdits.append(QLineEdit())
self.captureEdits[i].setReadOnly(True)
self.captureLabels[0].setText("Match:")
checkBoxLayout = QHBoxLayout()
checkBoxLayout.addWidget(self.caseSensitiveCheckBox)
checkBoxLayout.addWidget(self.minimalCheckBox)
checkBoxLayout.addStretch(1)
mainLayout = QGridLayout()
mainLayout.addWidget(patternLabel, 0, 0)
mainLayout.addWidget(self.patternComboBox, 0, 1)
mainLayout.addWidget(escapedPatternLabel, 1, 0)
mainLayout.addWidget(self.escapedPatternLineEdit, 1, 1)
mainLayout.addWidget(syntaxLabel, 2, 0)
mainLayout.addWidget(self.syntaxComboBox, 2, 1)
mainLayout.addLayout(checkBoxLayout, 3, 0, 1, 2)
mainLayout.addWidget(textLabel, 4, 0)
mainLayout.addWidget(self.textComboBox, 4, 1)
mainLayout.addWidget(indexLabel, 5, 0)
mainLayout.addWidget(self.indexEdit, 5, 1)
mainLayout.addWidget(matchedLengthLabel, 6, 0)
mainLayout.addWidget(self.matchedLengthEdit, 6, 1)
for i in range(self.MaxCaptures):
mainLayout.addWidget(self.captureLabels[i], 7 + i, 0)
mainLayout.addWidget(self.captureEdits[i], 7 + i, 1)
self.setLayout(mainLayout)
self.patternComboBox.editTextChanged.connect(self.refresh)
self.textComboBox.editTextChanged.connect(self.refresh)
self.caseSensitiveCheckBox.toggled.connect(self.refresh)
self.minimalCheckBox.toggled.connect(self.refresh)
self.syntaxComboBox.currentIndexChanged.connect(self.refresh)
self.patternComboBox.addItem("[A-Za-z_]+([A-Za-z_0-9]*)")
self.textComboBox.addItem("(10 + delta4)* 32")
self.setWindowTitle("RegExp")
self.setFixedHeight(self.sizeHint().height())
self.refresh()
def refresh(self):
#.........這裏部分代碼省略.........
示例6: SearchWidget
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setPalette [as 別名]
class SearchWidget (QWidget):
searched = pyqtSignal()
def __init__ (self, parent):
super().__init__(parent)
layout = QHBoxLayout(self)
self.inputline = QLineEdit(self)
self.inputline.editingFinished.connect(self.search)
self.inputline.setPlaceholderText("Search")
searchbutton = QPushButton(self)
searchbutton.setIcon(QIcon.fromTheme("edit-find"))
searchbutton.setToolTip("Search")
searchbutton.clicked.connect(self.search)
advbutton = QPushButton(self)
advbutton.setIcon(QIcon.fromTheme("preferences-other"))
advbutton.setToolTip("Search Fields")
advbutton.clicked.connect(self.advancedpopup)
self.popup = None
self.fields = {"text": True}
checks = OrderedDict()
checks["Text"] = (("Text", "text"), ("Speaker", "speaker"), ("Listener", "listener"))
checks["Enter Scripts"] = (("Function name", "entername"), ("Arguments", "enterarg"))
checks["Exit Scripts"] = (("Function name", "exitname"), ("Arguments", "exitarg"))
checks["Condition"] = (("Function name", "condname"), ("Arguments", "condarg"))
checks["Properties"] = (("Persistence", "persistence"), ("Bank mode", "bankmode"), ("Question hub", "questionhub"), ("Random weight", "randweight"), ("Comment", "comment"))
popup = QWidget(FlGlob.mainwindow, Qt.Dialog)
popup.setWindowTitle("Fields")
poplayout = QVBoxLayout(popup)
for group in checks.keys():
box = QGroupBox(group, popup)
boxlayout = QVBoxLayout(box)
for label, field in checks[group]:
check = QCheckBox(label, box)
check.stateChanged.connect(self.adv_factory(field))
if field in self.fields:
check.setChecked(self.fields[field])
boxlayout.addWidget(check)
boxlayout.addStretch()
poplayout.addWidget(box)
self.popup = popup
layout.addWidget(self.inputline)
layout.addWidget(searchbutton)
layout.addWidget(advbutton)
def search (self):
palette = QPalette()
defbase = palette.color(QPalette.Base)
deftext = palette.color(QPalette.Text)
query = self.inputline.text().casefold()
view = self.parent().view
if view is not None:
view.search(query, self.fields)
self.searched.emit()
if view.hits is None:
palette.setColor(QPalette.Base, defbase)
palette.setColor(QPalette.Text, deftext)
elif view.hits:
palette.setColor(QPalette.Base, FlPalette.hit)
palette.setColor(QPalette.Text, FlPalette.dark)
else:
palette.setColor(QPalette.Base, FlPalette.miss)
palette.setColor(QPalette.Text, FlPalette.dark)
self.inputline.setPalette(palette)
def adv_factory (self, field):
def adv (state):
self.fields[field] = bool(state)
return adv
@pyqtSlot()
def advancedpopup (self):
self.popup.setVisible(not self.popup.isVisible())
示例7: ExtractorWidget
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setPalette [as 別名]
class ExtractorWidget(QWidget):
def __init__(self, parent, model):
super(ExtractorWidget, self).__init__(parent)
self.setAttribute(Qt.WA_DeleteOnClose) # This is required to stop background timers!
self.on_remove = lambda: None
self._model = model
self._update_timer = QTimer(self)
self._update_timer.setSingleShot(False)
self._update_timer.timeout.connect(self._update)
self._update_timer.start(200)
self._delete_button = make_icon_button('trash-o', 'Remove this extractor', self, on_clicked=self._do_remove)
self._color_button = make_icon_button('paint-brush', 'Change plot color', self, on_clicked=self._change_color)
self._color_button.setFlat(True)
_set_color(self._color_button, QPalette.Button, model.color)
self._extraction_expression_box = QLineEdit(self)
self._extraction_expression_box.setToolTip('Extraction expression')
self._extraction_expression_box.setFont(get_monospace_font())
self._extraction_expression_box.setText(model.extraction_expression.source)
self._extraction_expression_box.textChanged.connect(self._on_extraction_expression_changed)
self._extraction_expression_box.setCompleter(
_make_expression_completer(self._extraction_expression_box, model.data_type_name))
self._error_label = make_icon_button('warning', 'Extraction error count; click to reset', self,
on_clicked=self._reset_errors)
self._reset_errors()
def box(text, tool_tip):
w = QLineEdit(self)
w.setReadOnly(True)
w.setFont(get_monospace_font())
w.setText(str(text))
w.setToolTip(tool_tip)
fm = QFontMetrics(w.font())
magic_number = 10
text_size = fm.size(0, w.text())
w.setMinimumWidth(text_size.width() + magic_number)
return w
layout = QHBoxLayout(self)
layout.addWidget(self._delete_button)
layout.addWidget(self._color_button)
layout.addWidget(box(model.data_type_name, 'Message type name'))
layout.addWidget(box(' AND '.join([x.source for x in model.filter_expressions]), 'Filter expressions'))
layout.addWidget(self._extraction_expression_box, 1)
layout.addWidget(self._error_label)
layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(layout)
def _on_extraction_expression_changed(self):
text = self._extraction_expression_box.text()
try:
expr = Expression(text)
self._extraction_expression_box.setPalette(QApplication.palette())
except Exception:
_set_color(self._extraction_expression_box, QPalette.Base, Qt.red)
return
self._model.extraction_expression = expr
def _change_color(self):
col = _show_color_dialog(self._model.color, self)
if col:
self._model.color = col
_set_color(self._color_button, QPalette.Button, self._model.color)
def _update(self):
self._error_label.setText(str(self._model.error_count))
def _reset_errors(self):
self._model.reset_error_count()
self._update()
def _do_remove(self):
self.on_remove()
self._update_timer.stop()
self.setParent(None)
self.close()
self.deleteLater()
示例8: ReTextWindow
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setPalette [as 別名]
#.........這裏部分代碼省略.........
self.enableSpellCheck(self.actionEnableSC.isChecked())
if setdefault:
globalSettings.spellCheckLocale = sl
def searchBarVisibilityChanged(self, visible):
self.actionSearch.setChecked(visible)
if visible:
self.searchEdit.setFocus(Qt.ShortcutFocusReason)
def find(self, back=False):
flags = QTextDocument.FindFlags()
if back:
flags |= QTextDocument.FindBackward
if self.csBox.isChecked():
flags |= QTextDocument.FindCaseSensitively
text = self.searchEdit.text()
editBox = self.editBoxes[self.ind]
cursor = editBox.textCursor()
newCursor = editBox.document().find(text, cursor, flags)
if not newCursor.isNull():
editBox.setTextCursor(newCursor)
return self.setSearchEditColor(True)
cursor.movePosition(QTextCursor.End if back else QTextCursor.Start)
newCursor = editBox.document().find(text, cursor, flags)
if not newCursor.isNull():
editBox.setTextCursor(newCursor)
return self.setSearchEditColor(True)
self.setSearchEditColor(False)
def setSearchEditColor(self, found):
palette = self.searchEdit.palette()
palette.setColor(QPalette.Active, QPalette.Base,
Qt.white if found else QColor(255, 102, 102))
self.searchEdit.setPalette(palette)
def getHtml(self, includeStyleSheet=True, includeTitle=True,
includeMeta=False, webenv=False):
if self.markups[self.ind] is None:
markupClass = self.getMarkupClass()
errMsg = self.tr('Could not parse file contents, check if '
'you have the <a href="%s">necessary module</a> installed!')
try:
errMsg %= markupClass.attributes[MODULE_HOME_PAGE]
except (AttributeError, KeyError):
# Remove the link if markupClass doesn't have the needed attribute
errMsg = errMsg.replace('<a href="%s">', '')
errMsg = errMsg.replace('</a>', '')
return '<p style="color: red">%s</p>' % errMsg
text = self.editBoxes[self.ind].toPlainText()
headers = ''
if includeStyleSheet:
headers += '<style type="text/css">\n' + self.ss + '</style>\n'
cssFileName = self.getDocumentTitle(baseName=True)+'.css'
if QFile(cssFileName).exists():
headers += '<link rel="stylesheet" type="text/css" href="%s">\n' \
% cssFileName
if includeMeta:
headers += ('<meta name="generator" content="ReText %s">\n' %
app_version)
fallbackTitle = self.getDocumentTitle() if includeTitle else ''
return self.markups[self.ind].get_whole_html(text,
custom_headers=headers, include_stylesheet=includeStyleSheet,
fallback_title=fallbackTitle, webenv=webenv)
def updatePreviewBox(self):
self.previewBlocked = False
示例9: FileEdit
# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import setPalette [as 別名]
class FileEdit(QWidget):
filePathChanged = pyqtSignal(str)
def __init__(self, parent = None):
super().__init__(parent)
self.mFilter = ''
self.mErrorTextColor = Qt.red
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self.mLineEdit = QLineEdit(self)
self.mLineEdit.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred))
self.mOkTextColor = self.mLineEdit.palette().color(QPalette.Active, QPalette.Text)
button = QToolButton(self)
button.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred))
button.setFixedWidth(20)
button.setText("...")
layout.addWidget(self.mLineEdit)
layout.addWidget(button)
self.setFocusProxy(self.mLineEdit)
self.setFocusPolicy(Qt.StrongFocus)
self.setAttribute(Qt.WA_InputMethodEnabled)
self.mLineEdit.textEdited.connect(self.filePathChanged)
self.mLineEdit.textChanged.connect(self.validate)
button.clicked.connect(self.buttonClicked)
def setFilePath(self, filePath):
if (self.mLineEdit.text() != filePath):
self.mLineEdit.setText(filePath)
def filePath(self):
return self.mLineEdit.text()
def setFilter(self, filter):
self.mFilter = filter
def focusInEvent(self, e):
self.mLineEdit.event(e)
if (e.reason() == Qt.TabFocusReason or e.reason() == Qt.BacktabFocusReason):
self.mLineEdit.selectAll()
super().focusInEvent(e)
def focusOutEvent(self, e):
self.mLineEdit.event(e)
super().focusOutEvent(e)
def keyPressEvent(self, e):
self.mLineEdit.event(e)
def keyReleaseEvent(self, e):
self.mLineEdit.event(e)
def validate(self, text):
if QFile.exists(text):
textColor = self.mOkTextColor
else:
textColor = self.mErrorTextColor
palette = self.mLineEdit.palette()
palette.setColor(QPalette.Active, QPalette.Text, textColor)
self.mLineEdit.setPalette(palette)
def buttonClicked(self):
filePath, _ = QFileDialog.getOpenFileName(self.window(), self.tr("Choose a File"), self.mLineEdit.text(), self.mFilter)
if filePath=='':
return
self.mLineEdit.setText(filePath)
self.filePathChanged.emit(filePath)