本文整理汇总了Python中AnyQt.QtWidgets.QLabel.setText方法的典型用法代码示例。如果您正苦于以下问题:Python QLabel.setText方法的具体用法?Python QLabel.setText怎么用?Python QLabel.setText使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类AnyQt.QtWidgets.QLabel
的用法示例。
在下文中一共展示了QLabel.setText方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ShowInfo
# 需要导入模块: from AnyQt.QtWidgets import QLabel [as 别名]
# 或者: from AnyQt.QtWidgets.QLabel import setText [as 别名]
def ShowInfo(self):
dialog = QDialog(self)
dialog.setModal(False)
dialog.setLayout(QVBoxLayout())
label = QLabel(dialog)
label.setText("Ontology:\n" + self.ontology.header
if self.ontology else "Ontology not loaded!")
dialog.layout().addWidget(label)
label = QLabel(dialog)
label.setText("Annotations:\n" + self.annotations.header.replace("!", "")
if self.annotations else "Annotations not loaded!")
dialog.layout().addWidget(label)
dialog.show()
示例2: DummyOWWidget
# 需要导入模块: from AnyQt.QtWidgets import QLabel [as 别名]
# 或者: from AnyQt.QtWidgets.QLabel import setText [as 别名]
class DummyOWWidget(widget.OWWidget):
"""
Dummy OWWidget used to report import/init errors in the canvas.
"""
name = "Placeholder"
# Fake settings handler that preserves the settings
class DummySettingsHandler(settings.SettingsHandler):
def pack_data(self, widget):
return getattr(widget, "_settings", {})
def initialize(self, widget, data=None):
widget._settings = data
settings.SettingsHandler.initialize(self, widget, None)
# specifically disable persistent global defaults
def write_defaults(self):
pass
def read_defaults(self):
pass
settingsHandler = DummySettingsHandler()
want_main_area = False
def __init__(self, parent=None):
super().__init__(parent)
self.errorLabel = QLabel(
textInteractionFlags=Qt.TextSelectableByMouse,
wordWrap=True,
)
self.errorLabel.setSizePolicy(
QSizePolicy.Expanding,
QSizePolicy.Expanding
)
self.controlArea.layout().addWidget(self.errorLabel)
def setErrorMessage(self, message):
self.errorLabel.setText(message)
self.error(message)
示例3: mousePressEvent
# 需要导入模块: from AnyQt.QtWidgets import QLabel [as 别名]
# 或者: from AnyQt.QtWidgets.QLabel import setText [as 别名]
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
if self.__popuptext:
popup = QMenu(self)
label = QLabel(
self, textInteractionFlags=Qt.TextBrowserInteraction,
openExternalLinks=self.__openExternalLinks,
)
label.setText(self.__styled(self.__defaultStyleSheet,
self.__popuptext))
label.linkActivated.connect(self.linkActivated)
label.linkHovered.connect(self.linkHovered)
action = QWidgetAction(popup)
action.setDefaultWidget(label)
popup.addAction(action)
popup.popup(event.globalPos(), action)
event.accept()
return
else:
super().mousePressEvent(event)
示例4: OWDataSets
# 需要导入模块: from AnyQt.QtWidgets import QLabel [as 别名]
# 或者: from AnyQt.QtWidgets.QLabel import setText [as 别名]
#.........这里部分代码省略.........
item1 = QStandardItem()
item1.setData(" " if datainfo.islocal else "", Qt.DisplayRole)
item1.setData(datainfo, Qt.UserRole)
item2 = QStandardItem(datainfo.title)
item3 = QStandardItem()
item3.setData(datainfo.size, Qt.DisplayRole)
item4 = QStandardItem()
item4.setData(datainfo.instances, Qt.DisplayRole)
item5 = QStandardItem()
item5.setData(datainfo.variables, Qt.DisplayRole)
item6 = QStandardItem()
item6.setData(datainfo.target, Qt.DisplayRole)
if datainfo.target:
item6.setIcon(variable_icon(datainfo.target))
item7 = QStandardItem()
item7.setData(", ".join(datainfo.tags) if datainfo.tags else "",
Qt.DisplayRole)
row = [item1, item2, item3, item4, item5, item6, item7]
model.appendRow(row)
if os.path.join(*file_path) == self.selected_id:
current_index = i
hs = self.view.header().saveState()
model_ = self.view.model().sourceModel()
self.view.model().setSourceModel(model)
self.view.header().restoreState(hs)
model_.deleteLater()
model_.setParent(None)
self.view.selectionModel().selectionChanged.connect(
self.__on_selection
)
# Update the info text
self.infolabel.setText(format_info(model.rowCount(), len(allinfolocal)))
if current_index != -1:
selmodel = self.view.selectionModel()
selmodel.select(
self.view.model().mapFromSource(model.index(current_index, 0)),
QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows)
def __update_cached_state(self):
model = self.view.model().sourceModel()
localinfo = self.list_local()
assert isinstance(model, QStandardItemModel)
allinfo = []
for i in range(model.rowCount()):
item = model.item(i, 0)
info = item.data(Qt.UserRole)
info.islocal = (info.prefix, info.filename) in localinfo
item.setData(" " if info.islocal else "", Qt.DisplayRole)
allinfo.append(info)
self.infolabel.setText(format_info(
model.rowCount(), sum(info.islocal for info in allinfo)))
def selected_dataset(self):
"""
Return the current selected data set info or None if not selected
Returns
-------
info : Optional[namespace]
"""
rows = self.view.selectionModel().selectedRows(0)
assert 0 <= len(rows) <= 1
示例5: OWDatabasesUpdate
# 需要导入模块: from AnyQt.QtWidgets import QLabel [as 别名]
# 或者: from AnyQt.QtWidgets.QLabel import setText [as 别名]
#.........这里部分代码省略.........
break
def toggleButtons(self):
selected_items = [item for item, tree_item, _ in self.updateItems if not tree_item.isHidden()]
self.buttonCheck(selected_items, OUTDATED, self.updateButton)
self.buttonCheck(selected_items, AVAILABLE, self.downloadButton)
def HandleError(self, exception):
if isinstance(exception, ConnectionError):
self.warning(0,
"Could not connect to server! Check your connection "
"and try to reconnect.")
self.SetFilesList({})
self.retryButton.show()
else:
sys.excepthook(type(exception), exception, None)
self.progress.setRange(0, 0)
self.setEnabled(True)
def UpdateInfoLabel(self):
local = [item for item, tree_item, _ in self.updateItems
if item.state != AVAILABLE and not tree_item.isHidden()]
size = sum(float(item.size) for item in local)
onServer = [item for item, tree_item, _ in self.updateItems if not tree_item.isHidden()]
sizeOnServer = sum(float(item.size) for item in onServer)
text = ("%i items, %s (on server: %i items, %s)" %
(len(local),
sizeof_fmt(size),
len(onServer),
sizeof_fmt(sizeOnServer)))
self.infoLabel.setText(text)
def UpdateAll(self):
self.warning(0)
for item, tree_item, _ in self.updateItems:
if item.state == OUTDATED and not tree_item.isHidden():
self.SubmitDownloadTask(item.domain, item.filename)
def DownloadFiltered(self):
# TODO: submit items in the order shown.
for item, tree_item, _ in self.updateItems:
if not tree_item.isHidden() and item.state in \
[AVAILABLE, OUTDATED]:
self.SubmitDownloadTask(item.domain, item.filename)
def SearchUpdate(self, searchString=None):
strings = str(self.lineEditFilter.text()).split()
for item, tree_item, _ in self.updateItems:
hide = not all(UpdateItem_match(item, string)
for string in strings)
tree_item.setHidden(hide)
self.UpdateInfoLabel()
self.toggleButtons()
def SubmitDownloadTask(self, domain, filename):
"""
Submit the (domain, filename) to be downloaded/updated.
"""
self.cancelButton.setEnabled(True)
index = self.updateItemIndex(domain, filename)
_, tree_item, opt_widget = self.updateItems[index]
示例6: OWTreeGraph
# 需要导入模块: from AnyQt.QtWidgets import QLabel [as 别名]
# 或者: from AnyQt.QtWidgets.QLabel import setText [as 别名]
#.........这里部分代码省略.........
self.toggle_node_color_reg()
self.set_node_info()
def color_changed(self, i):
if self.domain.class_var.is_discrete:
self.target_class_index = i
self.toggle_node_color_cls()
else:
self.regression_colors = i
self.toggle_node_color_reg()
def toggle_node_size(self):
self.set_node_info()
self.scene.update()
self.scene_view.repaint()
def toggle_color_cls(self):
self.toggle_node_color_cls()
self.set_node_info()
self.scene.update()
def toggle_color_reg(self):
self.toggle_node_color_reg()
self.set_node_info()
self.scene.update()
def ctree(self, model=None):
"""Input signal handler"""
self.clear_scene()
self.color_combo.clear()
self.closeContext()
self.model = model
if model is None:
self.info.setText('No tree.')
self.root_node = None
self.dataset = None
else:
self.domain = model.domain
self.dataset = model.instances
if self.dataset is not None and self.dataset.domain != self.domain:
self.clf_dataset = Table.from_table(model.domain, self.dataset)
else:
self.clf_dataset = self.dataset
class_var = self.domain.class_var
if class_var.is_discrete:
self.scene.colors = [QColor(*col) for col in class_var.colors]
self.color_label.setText("Target class: ")
self.color_combo.addItem("None")
self.color_combo.addItems(self.domain.class_vars[0].values)
self.color_combo.setCurrentIndex(self.target_class_index)
else:
self.scene.colors = \
ContinuousPaletteGenerator(*model.domain.class_var.colors)
self.color_label.setText("Color by: ")
self.color_combo.addItems(self.COL_OPTIONS)
self.color_combo.setCurrentIndex(self.regression_colors)
self.openContext(self.domain.class_var)
self.root_node = self.walkcreate(model.root, None)
self.info.setText('{} nodes, {} leaves'.
format(model.node_count(), model.leaf_count()))
self.setup_scene()
self.send("Selected Data", None)
self.send(ANNOTATED_DATA_SIGNAL_NAME,
create_annotated_table(self.dataset, []))
def walkcreate(self, node_inst, parent=None):
示例7: OWDataSets
# 需要导入模块: from AnyQt.QtWidgets import QLabel [as 别名]
# 或者: from AnyQt.QtWidgets.QLabel import setText [as 别名]
#.........这里部分代码省略.........
# set results from `list_remote` query.
assert QThread.currentThread() is self.thread()
assert f.done()
self.setBlocking(False)
self.setStatusMessage("")
self.allinfo_local = self.list_local()
try:
self.allinfo_remote = f.result()
except Exception: # anytying can happen, pylint: disable=broad-except
log.exception("Error while fetching updated index")
if not self.allinfo_local:
self.Error.no_remote_datasets()
else:
self.Warning.only_local_datasets()
self.allinfo_remote = {}
model, current_index = self.create_model()
self.view.model().setSourceModel(model)
self.view.selectionModel().selectionChanged.connect(
self.__on_selection
)
self.view.resizeColumnToContents(0)
self.view.setColumnWidth(
1, min(self.view.sizeHintForColumn(1),
self.view.fontMetrics().width("X" * 24)))
header = self.view.header()
header.restoreState(self.header_state)
# Update the info text
self.infolabel.setText(
format_info(model.rowCount(), len(self.allinfo_local)))
if current_index != -1:
selmodel = self.view.selectionModel()
selmodel.select(
self.view.model().mapFromSource(model.index(current_index, 0)),
QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows)
def __update_cached_state(self):
model = self.view.model().sourceModel()
localinfo = self.list_local()
assert isinstance(model, QStandardItemModel)
allinfo = []
for i in range(model.rowCount()):
item = model.item(i, 0)
info = item.data(Qt.UserRole)
info.islocal = info.file_path in localinfo
item.setData(" " if info.islocal else "", Qt.DisplayRole)
allinfo.append(info)
self.infolabel.setText(format_info(
model.rowCount(), sum(info.islocal for info in allinfo)))
def selected_dataset(self):
"""
Return the current selected dataset info or None if not selected
Returns
-------
info : Optional[Namespace]
"""
rows = self.view.selectionModel().selectedRows(0)
示例8: WelcomeDialog
# 需要导入模块: from AnyQt.QtWidgets import QLabel [as 别名]
# 或者: from AnyQt.QtWidgets.QLabel import setText [as 别名]
class WelcomeDialog(QDialog):
"""
A welcome widget shown at startup presenting a series
of buttons (actions) for a beginner to choose from.
"""
triggered = Signal(QAction)
def __init__(self, *args, **kwargs):
showAtStartup = kwargs.pop("showAtStartup", True)
feedbackUrl = kwargs.pop("feedbackUrl", "")
super().__init__(*args, **kwargs)
self.__triggeredAction = None
self.__showAtStartupCheck = None
self.__mainLayout = None
self.__feedbackUrl = None
self.__feedbackLabel = None
self.setupUi()
self.setFeedbackUrl(feedbackUrl)
self.setShowAtStartup(showAtStartup)
def setupUi(self):
self.setLayout(QVBoxLayout())
self.layout().setContentsMargins(0, 0, 0, 0)
self.layout().setSpacing(0)
self.__mainLayout = QVBoxLayout()
self.__mainLayout.setContentsMargins(0, 40, 0, 40)
self.__mainLayout.setSpacing(65)
self.layout().addLayout(self.__mainLayout)
self.setStyleSheet(WELCOME_WIDGET_BUTTON_STYLE)
bottom_bar = QWidget(objectName="bottom-bar")
bottom_bar_layout = QHBoxLayout()
bottom_bar_layout.setContentsMargins(20, 10, 20, 10)
bottom_bar.setLayout(bottom_bar_layout)
bottom_bar.setSizePolicy(QSizePolicy.MinimumExpanding,
QSizePolicy.Maximum)
self.__showAtStartupCheck = QCheckBox(
self.tr("Show at startup"), bottom_bar, checked=False
)
self.__feedbackLabel = QLabel(
textInteractionFlags=Qt.TextBrowserInteraction,
openExternalLinks=True,
visible=False,
)
bottom_bar_layout.addWidget(
self.__showAtStartupCheck, alignment=Qt.AlignVCenter | Qt.AlignLeft
)
bottom_bar_layout.addWidget(
self.__feedbackLabel, alignment=Qt.AlignVCenter | Qt.AlignRight
)
self.layout().addWidget(bottom_bar, alignment=Qt.AlignBottom,
stretch=1)
self.setSizeGripEnabled(False)
self.setFixedSize(620, 390)
def setShowAtStartup(self, show):
"""
Set the 'Show at startup' check box state.
"""
if self.__showAtStartupCheck.isChecked() != show:
self.__showAtStartupCheck.setChecked(show)
def showAtStartup(self):
"""
Return the 'Show at startup' check box state.
"""
return self.__showAtStartupCheck.isChecked()
def setFeedbackUrl(self, url):
# type: (str) -> None
"""
Set an 'feedback' url. When set a link is displayed in the bottom row.
"""
self.__feedbackUrl = url
if url:
text = self.tr("Help us improve!")
self.__feedbackLabel.setText(
'<a href="{url}">{text}</a>'.format(url=url, text=escape(text))
)
else:
self.__feedbackLabel.setText("")
self.__feedbackLabel.setVisible(bool(url))
def addRow(self, actions, background="light-orange"):
"""Add a row with `actions`.
"""
count = self.__mainLayout.count()
self.insertRow(count, actions, background)
def insertRow(self, index, actions, background="light-orange"):
"""Insert a row with `actions` at `index`.
#.........这里部分代码省略.........
示例9: MessagesWidget
# 需要导入模块: from AnyQt.QtWidgets import QLabel [as 别名]
# 或者: from AnyQt.QtWidgets.QLabel import setText [as 别名]
#.........这里部分代码省略.........
-------
messages: `List[Message]`
"""
return list(self.__messages.values())
def summarize(self):
# type: () -> Message
"""
Summarize all the messages into a single message.
"""
messages = [m for m in self.__messages.values() if not m.isEmpty()]
if messages:
return summarize(messages)
else:
return Message()
@staticmethod
def __styled(css, html):
# Prepend css style sheet before a html fragment.
if css.strip():
return "<style>\n" + escape(css) + "\n</style>\n" + html
else:
return html
def __update(self):
"""
Update the current display state.
"""
self.ensurePolished()
summary = self.summarize()
icon = message_icon(summary)
self.__iconwidget.setIcon(icon)
self.__iconwidget.setVisible(not (summary.isEmpty() or icon.isNull()))
self.__textlabel.setTextFormat(summary.textFormat)
self.__textlabel.setText(summary.text)
self.__textlabel.setVisible(bool(summary.text))
messages = [m for m in self.__messages.values() if not m.isEmpty()]
if messages:
messages = sorted(messages, key=attrgetter("severity"),
reverse=True)
fulltext = "<hr/>".join(m.asHtml() for m in messages)
else:
fulltext = ""
self.__fulltext = fulltext
self.setToolTip(self.__styled(self.__defaultStyleSheet, fulltext))
def is_short(m):
return not (m.informativeText or m.detailedText)
if not messages or len(messages) == 1 and is_short(messages[0]):
self.__popuptext = ""
else:
self.__popuptext = fulltext
self.__popupicon.setVisible(bool(self.__popuptext))
self.layout().activate()
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
if self.__popuptext:
popup = QMenu(self)
label = QLabel(
self, textInteractionFlags=Qt.TextBrowserInteraction,
openExternalLinks=self.__openExternalLinks,
)
label.setText(self.__styled(self.__defaultStyleSheet,
self.__popuptext))
示例10: PreviewBrowser
# 需要导入模块: from AnyQt.QtWidgets import QLabel [as 别名]
# 或者: from AnyQt.QtWidgets.QLabel import setText [as 别名]
class PreviewBrowser(QWidget):
"""A Preview Browser for recent/premade scheme selection.
"""
# Emitted when the current previewed item changes
currentIndexChanged = Signal(int)
# Emitted when an item is double clicked in the preview list.
activated = Signal(int)
def __init__(self, *args, heading="", previewMargins=12, **kwargs):
super().__init__(*args)
self.__model = None
self.__currentIndex = -1
self.__template = DESCRIPTION_TEMPLATE
self.__margin = previewMargins
self.__setupUi()
self.setHeading(heading)
def __setupUi(self):
vlayout = QVBoxLayout()
vlayout.setContentsMargins(0, 0, 0, 0)
top_layout = QVBoxLayout(objectName="top-layout")
margin = self.__margin
top_layout.setContentsMargins(margin, margin, margin, margin)
# Optional heading label
self.__heading = QLabel(
self, objectName="heading", visible=False
)
# Horizontal row with full text description and a large preview
# image.
hlayout = QHBoxLayout()
hlayout.setContentsMargins(0, 0, 0, 0)
self.__label = QLabel(
self, objectName="description-label",
wordWrap=True, alignment=Qt.AlignTop | Qt.AlignLeft
)
self.__label.setWordWrap(True)
self.__label.setFixedSize(220, PREVIEW_SIZE[1])
self.__label.setMinimumWidth(PREVIEW_SIZE[0] // 2)
self.__label.setMaximumHeight(PREVIEW_SIZE[1])
self.__image = QSvgWidget(self, objectName="preview-image")
self.__image.setFixedSize(*PREVIEW_SIZE)
self.__imageFrame = DropShadowFrame(self)
self.__imageFrame.setWidget(self.__image)
hlayout.addWidget(self.__label)
hlayout.addWidget(self.__image)
# Path text below the description and image
path_layout = QHBoxLayout()
path_layout.setContentsMargins(0, 0, 0, 0)
path_label = QLabel("<b>{0!s}</b>".format(self.tr("Path:")), self,
objectName="path-label")
self.__path = TextLabel(self, objectName="path-text")
path_layout.addWidget(path_label)
path_layout.addWidget(self.__path)
top_layout.addWidget(self.__heading)
top_layout.addLayout(hlayout)
top_layout.addLayout(path_layout)
vlayout.addLayout(top_layout)
# An list view with small preview icons.
self.__previewList = LinearIconView(
objectName="preview-list-view",
wordWrap=True
)
self.__previewList.doubleClicked.connect(self.__onDoubleClicked)
vlayout.addWidget(self.__previewList)
self.setLayout(vlayout)
def setHeading(self, text):
self.__heading.setVisible(bool(text))
self.__heading.setText(text)
def setPreviewMargins(self, margin):
# type: (int) -> None
"""
Set the left, top and right margins of the top widget part (heading
and description)
Parameters
----------
margin : int
Margin
"""
if margin != self.__margin:
layout = self.layout().itemAt(0).layout()
assert isinstance(layout, QVBoxLayout)
assert layout.objectName() == "top-layout"
layout.setContentsMargins(margin, margin, margin, 0)
def setModel(self, model):
#.........这里部分代码省略.........
示例11: MessageWidget
# 需要导入模块: from AnyQt.QtWidgets import QLabel [as 别名]
# 或者: from AnyQt.QtWidgets.QLabel import setText [as 别名]
class MessageWidget(QWidget):
"""
A widget displaying a simple message to the user.
This is an alternative to a full QMessageBox intended for inline
modeless messages.
[[icon] {Message text} (Ok) (Cancel)]
"""
#: Emitted when a button with the AcceptRole is clicked
accepted = Signal()
#: Emitted when a button with the RejectRole is clicked
rejected = Signal()
#: Emitted when a button with the HelpRole is clicked
helpRequested = Signal()
#: Emitted when a button is clicked
clicked = Signal(QAbstractButton)
class StandardButton(enum.IntEnum):
NoButton, Ok, Close, Help = 0x0, 0x1, 0x2, 0x4
NoButton, Ok, Close, Help = list(StandardButton)
class ButtonRole(enum.IntEnum):
InvalidRole, AcceptRole, RejectRole, HelpRole = 0, 1, 2, 3
InvalidRole, AcceptRole, RejectRole, HelpRole = list(ButtonRole)
_Button = namedtuple("_Button", ["button", "role", "stdbutton"])
def __init__(self, parent=None, icon=QIcon(), text="", wordWrap=False,
textFormat=Qt.AutoText, standardButtons=NoButton, **kwargs):
super().__init__(parent, **kwargs)
self.__text = text
self.__icon = QIcon()
self.__wordWrap = wordWrap
self.__standardButtons = MessageWidget.NoButton
self.__buttons = []
layout = QHBoxLayout()
layout.setContentsMargins(8, 0, 8, 0)
self.__iconlabel = QLabel(objectName="icon-label")
self.__iconlabel.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
self.__textlabel = QLabel(objectName="text-label", text=text,
wordWrap=wordWrap, textFormat=textFormat)
if sys.platform == "darwin":
self.__textlabel.setAttribute(Qt.WA_MacSmallSize)
layout.addWidget(self.__iconlabel)
layout.addWidget(self.__textlabel)
self.setLayout(layout)
self.setIcon(icon)
self.setStandardButtons(standardButtons)
def setText(self, text):
"""
Set the current message text.
:type message: str
"""
if self.__text != text:
self.__text = text
self.__textlabel.setText(text)
def text(self):
"""
Return the current message text.
:rtype: str
"""
return self.__text
def setIcon(self, icon):
"""
Set the message icon.
:type icon: QIcon | QPixmap | QString | QStyle.StandardPixmap
"""
if isinstance(icon, QStyle.StandardPixmap):
icon = self.style().standardIcon(icon)
else:
icon = QIcon(icon)
if self.__icon != icon:
self.__icon = QIcon(icon)
if not self.__icon.isNull():
size = self.style().pixelMetric(
QStyle.PM_SmallIconSize, None, self)
pm = self.__icon.pixmap(QSize(size, size))
else:
pm = QPixmap()
self.__iconlabel.setPixmap(pm)
self.__iconlabel.setVisible(not pm.isNull())
def icon(self):
"""
Return the current icon.
#.........这里部分代码省略.........
示例12: PreviewDialog
# 需要导入模块: from AnyQt.QtWidgets import QLabel [as 别名]
# 或者: from AnyQt.QtWidgets.QLabel import setText [as 别名]
class PreviewDialog(QDialog):
"""A Dialog for selecting an item from a PreviewItem.
"""
currentIndexChanged = Signal(int)
def __init__(self, parent=None, flags=Qt.WindowFlags(0),
model=None, **kwargs):
QDialog.__init__(self, parent, flags, **kwargs)
self.__setupUi()
if model is not None:
self.setModel(model)
def __setupUi(self):
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
self.setContentsMargins(0, 0, 0, 0)
heading = self.tr("Preview")
heading = "<h3>{0}</h3>".format(heading)
self.__heading = QLabel(heading, self,
objectName="heading")
self.__heading.setContentsMargins(12, 12, 12, 0)
self.__browser = previewbrowser.PreviewBrowser(self)
self.__buttons = QDialogButtonBox(QDialogButtonBox.Open | \
QDialogButtonBox.Cancel,
Qt.Horizontal,)
self.__buttons.button(QDialogButtonBox.Open).setAutoDefault(True)
# Set the Open dialog as disabled until the current index changes
self.__buttons.button(QDialogButtonBox.Open).setEnabled(False)
# The QDialogButtonsWidget messes with the layout if it is
# contained directly in the QDialog. So we create an extra
# layer of indirection.
buttons = QWidget(objectName="button-container")
buttons_l = QVBoxLayout()
buttons_l.setContentsMargins(12, 0, 12, 12)
buttons.setLayout(buttons_l)
buttons_l.addWidget(self.__buttons)
layout.addWidget(self.__heading)
layout.addWidget(self.__browser)
layout.addWidget(buttons)
self.__buttons.accepted.connect(self.accept)
self.__buttons.rejected.connect(self.reject)
self.__browser.currentIndexChanged.connect(
self.__on_currentIndexChanged
)
self.__browser.activated.connect(self.__on_activated)
layout.setSizeConstraint(QVBoxLayout.SetFixedSize)
self.setLayout(layout)
self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
def setItems(self, items):
"""Set the items (a list of strings) for preview/selection.
"""
model = QStringListModel(items)
self.setModel(model)
def setModel(self, model):
"""Set the model for preview/selection.
"""
self.__browser.setModel(model)
def model(self):
"""Return the model.
"""
return self.__browser.model()
def currentIndex(self):
return self.__browser.currentIndex()
def setCurrentIndex(self, index):
"""Set the current selected (shown) index.
"""
self.__browser.setCurrentIndex(index)
def setHeading(self, heading):
"""Set `heading` as the heading string ('<h3>Preview</h3>'
by default).
"""
self.__heading.setText(heading)
def heading(self):
"""Return the heading string.
"""
def __on_currentIndexChanged(self, index):
button = self.__buttons.button(QDialogButtonBox.Open)
button.setEnabled(index >= 0)
self.currentIndexChanged.emit(index)
#.........这里部分代码省略.........
示例13: OWMultifile
# 需要导入模块: from AnyQt.QtWidgets import QLabel [as 别名]
# 或者: from AnyQt.QtWidgets.QLabel import setText [as 别名]
class OWMultifile(Orange.widgets.data.owfile.OWFile, RecentPathsWidgetMixin):
name = "Multifile"
id = "orangecontrib.spectroscopy.widgets.files"
icon = "icons/multifile.svg"
description = "Read data from input files " \
"and send a data table to the output."
priority = 10000
replaces = ["orangecontrib.infrared.widgets.owfiles.OWFiles",
"orangecontrib.infrared.widgets.owmultifile.OWMultifile"]
file_idx = []
sheet = Orange.widgets.settings.Setting(None)
label = Orange.widgets.settings.Setting("")
recent_paths = Orange.widgets.settings.Setting([])
def __init__(self):
widget.OWWidget.__init__(self)
RecentPathsWidgetMixin.__init__(self)
self.domain = None
self.data = None
self.loaded_file = ""
self.sheets = []
self.lb = gui.listBox(self.controlArea, self, "file_idx",
selectionMode=QListWidget.MultiSelection)
layout = QGridLayout()
gui.widgetBox(self.controlArea, margin=0, orientation=layout)
file_button = gui.button(
None, self, ' ...', callback=self.browse_files, autoDefault=False)
file_button.setIcon(self.style().standardIcon(
QStyle.SP_DirOpenIcon))
file_button.setSizePolicy(Policy.Maximum, Policy.Fixed)
layout.addWidget(file_button, 0, 0)
remove_button = gui.button(
None, self, 'Remove', callback=self.remove_item)
clear_button = gui.button(
None, self, 'Clear', callback=self.clear)
layout.addWidget(remove_button, 0, 1)
layout.addWidget(clear_button, 0, 2)
reload_button = gui.button(
None, self, "Reload", callback=self.load_data, autoDefault=False)
reload_button.setIcon(self.style().standardIcon(QStyle.SP_BrowserReload))
reload_button.setSizePolicy(Policy.Fixed, Policy.Fixed)
layout.addWidget(reload_button, 0, 7)
self.sheet_box = gui.hBox(None, addToLayout=False, margin=0)
self.sheet_combo = gui.comboBox(None, self, "xls_sheet",
callback=self.select_sheet,
sendSelectedValue=True)
self.sheet_combo.setSizePolicy(
Policy.MinimumExpanding, Policy.Fixed)
self.sheet_label = QLabel()
self.sheet_label.setText('Sheet')
self.sheet_label.setSizePolicy(
Policy.MinimumExpanding, Policy.Fixed)
self.sheet_box.layout().addWidget(
self.sheet_label, Qt.AlignLeft)
self.sheet_box.layout().addWidget(
self.sheet_combo, Qt.AlignVCenter)
layout.addWidget(self.sheet_box, 2, 1)
self.sheet_box.hide()
layout.addWidget(self.sheet_box, 0, 5)
label_box = gui.hBox(None, addToLayout=False, margin=0)
label = gui.lineEdit(label_box, self, "label", callback=self.set_label,
label="Label", orientation=Qt.Horizontal)
layout.addWidget(label_box, 0, 6)
layout.setColumnStretch(3, 2)
box = gui.widgetBox(self.controlArea, "Columns (Double click to edit)")
self.domain_editor = DomainEditor(self)
self.editor_model = self.domain_editor.model()
box.layout().addWidget(self.domain_editor)
for i, rp in enumerate(self.recent_paths):
self.lb.addItem(rp.abspath)
# TODO unresolved paths just disappear! Modify _relocate_recent_files
box = gui.hBox(self.controlArea)
gui.rubber(box)
box.layout().addWidget(self.report_button)
self.report_button.setFixedWidth(170)
self.apply_button = gui.button(
box, self, "Apply", callback=self.apply_domain_edit)
self.apply_button.setEnabled(False)
self.apply_button.setFixedWidth(170)
self.editor_model.dataChanged.connect(
lambda: self.apply_button.setEnabled(True))
#.........这里部分代码省略.........
示例14: OWImportImages
# 需要导入模块: from AnyQt.QtWidgets import QLabel [as 别名]
# 或者: from AnyQt.QtWidgets.QLabel import setText [as 别名]
#.........这里部分代码省略.........
hbox.layout().addWidget(reloadbutton)
self.addActions([browseaction, reloadaction])
reloadaction.changed.connect(
lambda: reloadbutton.setEnabled(reloadaction.isEnabled())
)
box = gui.vBox(vbox, "Info")
self.infostack = QStackedWidget()
self.info_area = QLabel(
text="No image set selected",
wordWrap=True
)
self.progress_widget = QProgressBar(
minimum=0, maximum=0
)
self.cancel_button = QPushButton(
"Cancel", icon=icons.cancel_icon,
)
self.cancel_button.clicked.connect(self.cancel)
w = QWidget()
vlayout = QVBoxLayout()
vlayout.setContentsMargins(0, 0, 0, 0)
hlayout = QHBoxLayout()
hlayout.setContentsMargins(0, 0, 0, 0)
hlayout.addWidget(self.progress_widget)
hlayout.addWidget(self.cancel_button)
vlayout.addLayout(hlayout)
self.pathlabel = TextLabel()
self.pathlabel.setTextElideMode(Qt.ElideMiddle)
self.pathlabel.setAttribute(Qt.WA_MacSmallSize)
vlayout.addWidget(self.pathlabel)
w.setLayout(vlayout)
self.infostack.addWidget(self.info_area)
self.infostack.addWidget(w)
box.layout().addWidget(self.infostack)
self.__initRecentItemsModel()
self.__invalidated = True
self.__executor = ThreadExecutor(self)
QApplication.postEvent(self, QEvent(RuntimeEvent.Init))
def __initRecentItemsModel(self):
self._relocate_recent_files()
recent_paths = []
for item in self.recent_paths:
recent_paths.append(item)
recent_paths = recent_paths[:OWImportImages.MaxRecentItems]
recent_model = self.recent_cb.model()
recent_model.clear()
for pathitem in recent_paths:
item = RecentPath_asqstandarditem(pathitem)
recent_model.appendRow(item)
self.recent_paths = recent_paths
if self.recent_paths and os.path.isdir(self.recent_paths[0].abspath):
示例15: OWNNLearner
# 需要导入模块: from AnyQt.QtWidgets import QLabel [as 别名]
# 或者: from AnyQt.QtWidgets.QLabel import setText [as 别名]
class OWNNLearner(OWBaseLearner):
name = "Neural Network"
description = "A multi-layer perceptron (MLP) algorithm with " \
"backpropagation."
icon = "icons/NN.svg"
priority = 90
keywords = ["mlp"]
LEARNER = NNLearner
activation = ["identity", "logistic", "tanh", "relu"]
act_lbl = ["Identity", "Logistic", "tanh", "ReLu"]
solver = ["lbfgs", "sgd", "adam"]
solv_lbl = ["L-BFGS-B", "SGD", "Adam"]
learner_name = Setting("Neural Network")
hidden_layers_input = Setting("100,")
activation_index = Setting(3)
solver_index = Setting(2)
max_iterations = Setting(200)
alpha_index = Setting(0)
settings_version = 1
alphas = list(chain([x / 10000 for x in range(1, 10)],
[x / 1000 for x in range(1, 10)],
[x / 100 for x in range(1, 10)],
[x / 10 for x in range(1, 10)],
range(1, 10),
range(10, 100, 5),
range(100, 200, 10),
range(100, 1001, 50)))
def add_main_layout(self):
form = QFormLayout()
form.setFieldGrowthPolicy(form.AllNonFixedFieldsGrow)
form.setVerticalSpacing(25)
gui.widgetBox(self.controlArea, True, orientation=form)
form.addRow(
"Neurons in hidden layers:",
gui.lineEdit(
None, self, "hidden_layers_input",
orientation=Qt.Horizontal, callback=self.settings_changed,
tooltip="A list of integers defining neurons. Length of list "
"defines the number of layers. E.g. 4, 2, 2, 3.",
placeholderText="e.g. 100,"))
form.addRow(
"Activation:",
gui.comboBox(
None, self, "activation_index", orientation=Qt.Horizontal,
label="Activation:", items=[i for i in self.act_lbl],
callback=self.settings_changed))
form.addRow(" ", gui.separator(None, 16))
form.addRow(
"Solver:",
gui.comboBox(
None, self, "solver_index", orientation=Qt.Horizontal,
label="Solver:", items=[i for i in self.solv_lbl],
callback=self.settings_changed))
self.reg_label = QLabel()
slider = gui.hSlider(
None, self, "alpha_index",
minValue=0, maxValue=len(self.alphas) - 1,
callback=lambda: (self.set_alpha(), self.settings_changed()),
createLabel=False)
form.addRow(self.reg_label, slider)
self.set_alpha()
form.addRow(
"Maximal number of iterations:",
gui.spin(
None, self, "max_iterations", 10, 10000, step=10,
label="Max iterations:", orientation=Qt.Horizontal,
alignment=Qt.AlignRight, callback=self.settings_changed))
def set_alpha(self):
self.strength_C = self.alphas[self.alpha_index]
self.reg_label.setText("Regularization, α={}:".format(self.strength_C))
@property
def alpha(self):
return self.alphas[self.alpha_index]
def setup_layout(self):
super().setup_layout()
self._task = None # type: Optional[Task]
self._executor = ThreadExecutor()
# just a test cancel button
gui.button(self.apply_button, self, "Cancel", callback=self.cancel)
def create_learner(self):
return self.LEARNER(
hidden_layer_sizes=self.get_hidden_layers(),
activation=self.activation[self.activation_index],
solver=self.solver[self.solver_index],
alpha=self.alpha,
max_iter=self.max_iterations,
preprocessors=self.preprocessors)
#.........这里部分代码省略.........