本文整理汇总了Python中PyQt5.QtWidgets.QStackedWidget.count方法的典型用法代码示例。如果您正苦于以下问题:Python QStackedWidget.count方法的具体用法?Python QStackedWidget.count怎么用?Python QStackedWidget.count使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QStackedWidget
的用法示例。
在下文中一共展示了QStackedWidget.count方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: PyMultiPageWidget
# 需要导入模块: from PyQt5.QtWidgets import QStackedWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QStackedWidget import count [as 别名]
class PyMultiPageWidget(QWidget):
currentIndexChanged = pyqtSignal(int)
pageTitleChanged = pyqtSignal(str)
def __init__(self, parent=None):
super(PyMultiPageWidget, self).__init__(parent)
self.comboBox = QComboBox()
# MAGIC
# It is important that the combo box has an object name beginning
# with '__qt__passive_', otherwise, it is inactive in the form editor
# of the designer and you can't change the current page via the
# combo box.
# MAGIC
self.comboBox.setObjectName('__qt__passive_comboBox')
self.stackWidget = QStackedWidget()
self.comboBox.activated.connect(self.setCurrentIndex)
self.layout = QVBoxLayout()
self.layout.addWidget(self.comboBox)
self.layout.addWidget(self.stackWidget)
self.setLayout(self.layout)
def sizeHint(self):
return QSize(200, 150)
def count(self):
return self.stackWidget.count()
def widget(self, index):
return self.stackWidget.widget(index)
@pyqtSlot(QWidget)
def addPage(self, page):
self.insertPage(self.count(), page)
@pyqtSlot(int, QWidget)
def insertPage(self, index, page):
page.setParent(self.stackWidget)
self.stackWidget.insertWidget(index, page)
title = page.windowTitle()
if title == "":
title = "Page %d" % (self.comboBox.count() + 1)
page.setWindowTitle(title)
self.comboBox.insertItem(index, title)
@pyqtSlot(int)
def removePage(self, index):
widget = self.stackWidget.widget(index)
self.stackWidget.removeWidget(widget)
self.comboBox.removeItem(index)
def getPageTitle(self):
return self.stackWidget.currentWidget().windowTitle()
@pyqtSlot(str)
def setPageTitle(self, newTitle):
self.comboBox.setItemText(self.getCurrentIndex(), newTitle)
self.stackWidget.currentWidget().setWindowTitle(newTitle)
self.pageTitleChanged.emit(newTitle)
def getCurrentIndex(self):
return self.stackWidget.currentIndex()
@pyqtSlot(int)
def setCurrentIndex(self, index):
if index != self.getCurrentIndex():
self.stackWidget.setCurrentIndex(index)
self.comboBox.setCurrentIndex(index)
self.currentIndexChanged.emit(index)
pageTitle = pyqtProperty(str, fget=getPageTitle, fset=setPageTitle, stored=False)
currentIndex = pyqtProperty(int, fget=getCurrentIndex, fset=setCurrentIndex)
示例2: AppSettings
# 需要导入模块: from PyQt5.QtWidgets import QStackedWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QStackedWidget import count [as 别名]
class AppSettings(QDialog):
SettingsWidgets = []
def __init__(self, conf, **kwargs):
super().__init__(**kwargs)
self.conf = conf
self.setWindowTitle('LiSP preferences')
self.setWindowModality(QtCore.Qt.ApplicationModal)
self.setMaximumSize(635, 530)
self.setMinimumSize(635, 530)
self.resize(635, 530)
self.listWidget = QListWidget(self)
self.listWidget.setGeometry(QtCore.QRect(5, 10, 185, 470))
self.sections = QStackedWidget(self)
self.sections.setGeometry(QtCore.QRect(200, 10, 430, 470))
for widget in self.SettingsWidgets:
widget = widget(QtCore.QSize(430, 465), self)
widget.set_configuration(self.conf)
self.listWidget.addItem(widget.NAME)
self.sections.addWidget(widget)
if len(self.SettingsWidgets) > 0:
self.listWidget.setCurrentRow(0)
self.listWidget.currentItemChanged.connect(self._change_page)
self.dialogButtons = QDialogButtonBox(self)
self.dialogButtons.setGeometry(10, 495, 615, 30)
self.dialogButtons.setStandardButtons(QDialogButtonBox.Cancel |
QDialogButtonBox.Ok)
self.dialogButtons.rejected.connect(self.reject)
self.dialogButtons.accepted.connect(self.accept)
def get_configuraton(self):
conf = {}
for n in range(self.sections.count()):
widget = self.sections.widget(n)
newconf = widget.get_configuration()
deep_update(conf, newconf)
return conf
@classmethod
def register_settings_widget(cls, widget):
if widget not in cls.SettingsWidgets:
cls.SettingsWidgets.append(widget)
@classmethod
def unregister_settings_widget(cls, widget):
if widget not in cls.SettingsWidgets:
cls.SettingsWidgets.remove(widget)
def _change_page(self, current, previous):
if not current:
current = previous
self.sections.setCurrentIndex(self.listWidget.row(current))
示例3: GstMediaSettings
# 需要导入模块: from PyQt5.QtWidgets import QStackedWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QStackedWidget import count [as 别名]
class GstMediaSettings(SettingsSection):
Name = 'Media Settings'
def __init__(self, size, cue=None, parent=None):
super().__init__(size, cue=cue, parent=parent)
self._pipe = ''
self._conf = {}
self._check = False
self.glayout = QGridLayout(self)
self.listWidget = QListWidget(self)
self.glayout.addWidget(self.listWidget, 0, 0)
self.pipeButton = QPushButton('Change Pipe', self)
self.glayout.addWidget(self.pipeButton, 1, 0)
self.elements = QStackedWidget(self)
self.glayout.addWidget(self.elements, 0, 1, 2, 1)
self.glayout.setColumnStretch(0, 2)
self.glayout.setColumnStretch(1, 5)
self.listWidget.currentItemChanged.connect(self.__change_page)
self.pipeButton.clicked.connect(self.__edit_pipe)
def set_configuration(self, conf):
# Get the media section of the cue configuration
if conf is not None:
conf = conf.get('media', {})
# Activate the layout, so we can get the right widgets size
self.glayout.activate()
# Create a local copy of the configuration
self._conf = deepcopy(conf)
# Create the widgets
sections = sections_by_element_name()
for element in conf.get('pipe', '').split('!'):
widget = sections.get(element)
if widget is not None:
widget = widget(self.elements.size(), element, self)
widget.set_configuration(self._conf['elements'])
self.elements.addWidget(widget)
item = QListWidgetItem(widget.NAME)
self.listWidget.addItem(item)
self.listWidget.setCurrentRow(0)
def get_configuration(self):
conf = {'elements': {}}
for el in self.elements.children():
if isinstance(el, SettingsSection):
conf['elements'].update(el.get_configuration())
# If in check mode the pipeline is not returned
if not self._check:
conf['pipe'] = self._conf['pipe']
return {'media': conf}
def enable_check(self, enable):
self._check = enable
for element in self.elements.children():
if isinstance(element, SettingsSection):
element.enable_check(enable)
def __change_page(self, current, previous):
if not current:
current = previous
self.elements.setCurrentIndex(self.listWidget.row(current))
def __edit_pipe(self):
# Backup the settings
self._conf.update(self.get_configuration()['media'])
# Show the dialog
dialog = GstPipeEdit(self._conf.get('pipe', ''), parent=self)
if dialog.exec_() == dialog.Accepted:
# Reset the view
for _ in range(self.elements.count()):
self.elements.removeWidget(self.elements.widget(0))
self.listWidget.clear()
# Reload with the new pipeline
self._conf['pipe'] = dialog.get_pipe()
self.set_configuration({'media': self._conf})
self.enable_check(self._check)
示例4: SubTabWidget
# 需要导入模块: from PyQt5.QtWidgets import QStackedWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QStackedWidget import count [as 别名]
class SubTabWidget(QWidget):
_tabChanged = pyqtSignal(int, name = "tabChanged")
def __init__(self, subtitleData, videoWidget, parent = None):
super(SubTabWidget, self).__init__(parent)
self._subtitleData = subtitleData
self.__initTabWidget(videoWidget)
def __initTabWidget(self, videoWidget):
settings = SubSettings()
mainLayout = QVBoxLayout(self)
mainLayout.setContentsMargins(0, 0, 0, 0)
mainLayout.setSpacing(0)
#TabBar
self.tabBar = QTabBar(self)
# Splitter (bookmarks + pages)
self.splitter = QSplitter(self)
self.splitter.setObjectName("sidebar_splitter")
self._toolbox = ToolBox(self._subtitleData, self)
self._toolbox.setObjectName("sidebar")
self._toolbox.setMinimumWidth(100)
self._toolbox.addTool(Details(self._subtitleData, self))
self._toolbox.addTool(Synchronizer(videoWidget, self._subtitleData, self))
self._toolbox.addTool(History(self))
self.rightWidget = QWidget()
rightLayout = QGridLayout()
rightLayout.setContentsMargins(0, 0, 0, 0)
self.rightWidget.setLayout(rightLayout)
self._mainTab = FileList(_("Subtitles"), self._subtitleData, self)
self.pages = QStackedWidget(self)
rightLayout.addWidget(self.pages, 0, 0)
self.tabBar.addTab(self._mainTab.name)
self.pages.addWidget(self._mainTab)
self.splitter.addWidget(self._toolbox)
self.splitter.addWidget(self.rightWidget)
self.__drawSplitterHandle(1)
# Setting widgets
mainLayout.addWidget(self.tabBar)
mainLayout.addWidget(self.splitter)
# Widgets settings
self.tabBar.setMovable(True)
self.tabBar.setTabsClosable(True)
self.tabBar.setExpanding(False)
# Don't resize left panel if it's not needed
leftWidgetIndex = self.splitter.indexOf(self._toolbox)
rightWidgetIndex = self.splitter.indexOf(self.rightWidget)
self.splitter.setStretchFactor(leftWidgetIndex, 0)
self.splitter.setStretchFactor(rightWidgetIndex, 1)
self.splitter.setCollapsible(leftWidgetIndex, False)
self.splitter.setSizes([250])
# Some signals
self.tabBar.currentChanged.connect(self.showTab)
self.tabBar.tabCloseRequested.connect(self.closeTab)
self.tabBar.tabMoved.connect(self.moveTab)
self._mainTab.requestOpen.connect(self.openTab)
self._mainTab.requestRemove.connect(self.removeFile)
self.tabChanged.connect(lambda i: self._toolbox.setContentFor(self.tab(i)))
self.setLayout(mainLayout)
def __addTab(self, filePath):
"""Returns existing tab index. Creates a new one if it isn't opened and returns its index
otherwise."""
for i in range(self.tabBar.count()):
widget = self.pages.widget(i)
if not widget.isStatic and filePath == widget.filePath:
return i
tab = SubtitleEditor(filePath, self._subtitleData, self)
newIndex = self.tabBar.addTab(self._createTabName(tab.name, tab.history.isClean()))
tab.history.cleanChanged.connect(
lambda clean: self._cleanStateForFileChanged(filePath, clean))
self.pages.addWidget(tab)
return newIndex
def __drawSplitterHandle(self, index):
splitterHandle = self.splitter.handle(index)
splitterLayout = QVBoxLayout(splitterHandle)
splitterLayout.setSpacing(0)
splitterLayout.setContentsMargins(0, 0, 0, 0)
line = QFrame(splitterHandle)
line.setFrameShape(QFrame.HLine)
line.setFrameShadow(QFrame.Sunken)
#.........这里部分代码省略.........
示例5: ParamsByType
# 需要导入模块: from PyQt5.QtWidgets import QStackedWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QStackedWidget import count [as 别名]
#.........这里部分代码省略.........
Input:
current[ParamsByGroup]: The current group parameter table
to[ParamsByGroup]: The new group parameter table
"""
ct = current.findTable("Main")
tot = to.findTable("Main")
if not ct or not tot or ct == tot:
return
tot.removeUserParams()
params = ct.getUserParams()
tot.addUserParams(params)
to.syncParamsFrom(current)
# Make sure the name parameter stays the same
idx = ct.findRow("Name")
if idx >= 0:
name = ct.item(idx, 1).text()
idx = tot.findRow("Name")
if idx >= 0:
tot.item(idx, 1).setText(name)
def currentType(self):
return self.combo.currentText()
def save(self):
"""
Look at the user params in self.block.parameters.
update the type tables
Save type on block
"""
t = self.getTable()
if t:
t.save()
self.block.setBlockType(self.combo.currentText())
def reset(self):
t = self.getTable()
t.reset()
def getOrCreateTypeTable(self, type_name):
"""
Gets the table for the type name or create it if it doesn't exist.
Input:
type_name[str]: Name of the type
Return:
ParamsByGroup: The parameters corresponding to the type
"""
t = self.type_table_map.get(type_name)
if t:
return t
t = ParamsByGroup(self.block, self.type_params_map.get(type_name, self.block.orderedParameters()), self.type_block_map)
t.needBlockList.connect(self.needBlockList)
t.blockRenamed.connect(self.blockRenamed)
t.changed.connect(self.changed)
self.type_table_map[type_name] = t
self.table_stack.addWidget(t)
return t
def setDefaultBlockType(self):
param = self.block.getParamInfo("type")
if param and param.value:
self.setBlockType(param.value)
elif self.block.types:
self.setBlockType(sorted(self.block.types.keys())[0])
def setBlockType(self, type_name):
if type_name not in self.block.types:
return
t = self.getOrCreateTypeTable(type_name)
t.updateWatchers()
self.combo.blockSignals(True)
self.combo.setCurrentText(type_name)
self.combo.blockSignals(False)
t.updateType(type_name)
current = self.table_stack.currentWidget()
self._syncUserParams(current, t)
self.table_stack.setCurrentWidget(t)
self.changed.emit()
def addUserParam(self, param):
t = self.table_stack.currentWidget()
t.addUserParam(param)
def setWatchedBlockList(self, path, children):
for i in range(self.table_stack.count()):
t = self.table_stack.widget(i)
t.setWatchedBlockList(path, children)
def updateWatchers(self):
for i in range(self.table_stack.count()):
t = self.table_stack.widget(i)
t.updateWatchers()
def getTable(self):
return self.table_stack.currentWidget()
def paramValue(self, name):
for i in range(self.table_stack.count()):
t = self.table_stack.widget(i)
if t.paramValue(name):
return t.paramValue(name)
示例6: TableWidget
# 需要导入模块: from PyQt5.QtWidgets import QStackedWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QStackedWidget import count [as 别名]
class TableWidget(QSplitter):
def __init__(self):
super(TableWidget, self).__init__()
# vbox = QVBoxLayout(self)
# vbox.setContentsMargins(0, 0, 0, 0)
self._tabs = QTabWidget()
self._tabs.setAutoFillBackground(True)
p = self._tabs.palette()
p.setColor(p.Window, QColor("white"))
self._tabs.setPalette(p)
self._other_tab = QTabWidget()
self._other_tab.setAutoFillBackground(True)
self._other_tab.setPalette(p)
self.addWidget(self._tabs)
self.addWidget(self._other_tab)
self.setSizes([1, 1])
self._other_tab.hide()
self.relations = {}
# Stack
self.stacked = QStackedWidget()
self._tabs.addTab(self.stacked, "Workspace")
self.stacked_result = QStackedWidget()
self._tabs.addTab(self.stacked_result, self.tr("Resultados"))
btn_split = QToolButton()
btn_split.setToolTip(self.tr("Click para dividir la pantalla"))
btn_split.setAutoRaise(True)
btn_split.setIcon(QIcon(":img/split"))
self._tabs.setCornerWidget(btn_split)
btn_split.clicked.connect(self._split)
btn_split = QToolButton()
btn_split.setToolTip(self.tr("Click para juntar las pantallas"))
btn_split.setAutoRaise(True)
btn_split.setIcon(QIcon(":img/split"))
btn_split.clicked.connect(self._unsplit)
self._other_tab.setCornerWidget(btn_split)
# self.setContextMenuPolicy(Qt.CustomContextMenu)
# self.customContextMenuRequested.connect(self._show_menu)
lateral_widget = Pireal.get_service("lateral_widget")
lateral_widget.resultClicked.connect(self._on_result_list_clicked)
lateral_widget.resultSelectionChanged.connect(
lambda index: self.stacked_result.setCurrentIndex(index))
# lateral_widget.newRowsRequested.connect(self._insert_rows)
def insert_rows(self, tuplas):
current_view = self.current_table()
if current_view is not None:
model = current_view.model()
for tupla in tuplas:
model.insertRow(model.rowCount(), tupla)
current_view.adjust_columns()
def _on_result_list_clicked(self, index):
self.stacked_result.setCurrentIndex(index)
if not self._other_tab.isVisible():
self._tabs.setCurrentIndex(1)
def _unsplit(self):
self._other_tab.hide()
result_widget = self._other_tab.widget(0)
self._tabs.addTab(result_widget, self.tr("Resultados"))
self._tabs.cornerWidget().show()
def _split(self):
result_widget = self._tabs.widget(1)
self._other_tab.addTab(result_widget, self.tr("Resultados"))
self._other_tab.show()
self.setSizes([1, 1])
self._tabs.cornerWidget().hide()
self.setOrientation(Qt.Horizontal)
def _show_menu(self, position):
menu = QMenu(self)
if self.count() > 0:
add_tuple_action = menu.addAction(self.tr("Agregar Tupla"))
add_col_action = menu.addAction(self.tr("Add Column"))
add_tuple_action.triggered.connect(self.add_tuple)
add_col_action.triggered.connect(self.add_column)
menu.addSeparator()
add_relation_action = menu.addAction(self.tr("Create new Relation"))
add_relation_action.triggered.connect(self.__new_relation)
menu.exec_(self.mapToGlobal(position))
def __new_relation(self):
central_service = Pireal.get_service("central")
central_service.create_new_relation()
def count(self):
return self.stacked.count()
#.........这里部分代码省略.........
示例7: Settings
# 需要导入模块: from PyQt5.QtWidgets import QStackedWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QStackedWidget import count [as 别名]
class Settings(QDialog):
"""Window showing the Settings/settings.
Parameters
----------
parent : instance of QMainWindow
the main window
"""
def __init__(self, parent):
super().__init__(None, Qt.WindowSystemMenuHint | Qt.WindowTitleHint)
self.parent = parent
self.config = ConfigUtils(self.parent.update)
self.setWindowTitle('Settings')
self.create_settings()
def create_settings(self):
"""Create the widget, organized in two parts.
Notes
-----
When you add widgets in config, remember to update show_settings too
"""
bbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Apply |
QDialogButtonBox.Cancel)
self.idx_ok = bbox.button(QDialogButtonBox.Ok)
self.idx_apply = bbox.button(QDialogButtonBox.Apply)
self.idx_cancel = bbox.button(QDialogButtonBox.Cancel)
bbox.clicked.connect(self.button_clicked)
page_list = QListWidget()
page_list.setSpacing(1)
page_list.currentRowChanged.connect(self.change_widget)
pages = ['General', 'Overview', 'Signals', 'Channels', 'Spectrum',
'Notes', 'Video']
for one_page in pages:
page_list.addItem(one_page)
self.stacked = QStackedWidget()
self.stacked.addWidget(self.config)
self.stacked.addWidget(self.parent.overview.config)
self.stacked.addWidget(self.parent.traces.config)
self.stacked.addWidget(self.parent.channels.config)
self.stacked.addWidget(self.parent.spectrum.config)
self.stacked.addWidget(self.parent.notes.config)
self.stacked.addWidget(self.parent.video.config)
hsplitter = QSplitter()
hsplitter.addWidget(page_list)
hsplitter.addWidget(self.stacked)
btnlayout = QHBoxLayout()
btnlayout.addStretch(1)
btnlayout.addWidget(bbox)
vlayout = QVBoxLayout()
vlayout.addWidget(hsplitter)
vlayout.addLayout(btnlayout)
self.setLayout(vlayout)
def change_widget(self, new_row):
"""Change the widget on the right side.
Parameters
----------
new_row : int
index of the widgets
"""
self.stacked.setCurrentIndex(new_row)
def button_clicked(self, button):
"""Action when button was clicked.
Parameters
----------
button : instance of QPushButton
which button was pressed
"""
if button in (self.idx_ok, self.idx_apply):
# loop over widgets, to see if they were modified
for i_config in range(self.stacked.count()):
one_config = self.stacked.widget(i_config)
if one_config.modified:
lg.debug('Settings for ' + one_config.widget +
' were modified')
one_config.get_values()
if self.parent.info.dataset is not None:
one_config.update_widget()
one_config.modified = False
if button == self.idx_ok:
self.accept()
if button == self.idx_cancel:
self.reject()
示例8: QueryWidget
# 需要导入模块: from PyQt5.QtWidgets import QStackedWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QStackedWidget import count [as 别名]
#.........这里部分代码省略.........
new_editor.setDocument(actual_doc)
new_editor.resize(900, 400)
# Set text cursor
tc = self._query_editor.textCursor()
new_editor.setTextCursor(tc)
# Set title
db = Pireal.get_service("central").get_active_db()
qc = db.query_container
new_editor.setWindowTitle(qc.tab_text(qc.current_index()))
new_editor.show()
def __on_undo_available(self, value):
""" Change state of undo action """
pireal = Pireal.get_service("pireal")
action = pireal.get_action("undo_action")
action.setEnabled(value)
def __on_redo_available(self, value):
""" Change state of redo action """
pireal = Pireal.get_service("pireal")
action = pireal.get_action("redo_action")
action.setEnabled(value)
def __on_copy_available(self, value):
""" Change states of cut and copy action """
cut_action = Pireal.get_action("cut_action")
cut_action.setEnabled(value)
copy_action = Pireal.get_action("copy_action")
copy_action.setEnabled(value)
def show_relation(self, item):
central_widget = Pireal.get_service("central")
table_widget = central_widget.get_active_db().table_widget
rela = self.relations[item.name]
dialog = QDialog(self)
dialog.resize(700, 500)
dialog.setWindowTitle(item.name)
box = QVBoxLayout(dialog)
box.setContentsMargins(5, 5, 5, 5)
table = table_widget.create_table(rela)
box.addWidget(table)
hbox = QHBoxLayout()
btn = QPushButton(self.tr("Ok"))
btn.clicked.connect(dialog.close)
hbox.addStretch()
hbox.addWidget(btn)
box.addLayout(hbox)
dialog.show()
def save_sizes(self):
""" Save sizes of Splitters """
qsettings = QSettings(settings.SETTINGS_PATH, QSettings.IniFormat)
qsettings.setValue('hsplitter_query_sizes',
self._hsplitter.saveState())
qsettings.setValue('vsplitter_query_sizes',
self._vsplitter.saveState())
def get_editor(self):
return self._query_editor
def __editor_modified(self, modified):
self.editorModified.emit(modified)
def showEvent(self, event):
super(QueryWidget, self).showEvent(event)
self._hsplitter.setSizes([1, self.width() / 3])
def clear_results(self):
self._result_list.clear_items()
i = self._stack_tables.count()
while i >= 0:
widget = self._stack_tables.widget(i)
self._stack_tables.removeWidget(widget)
if widget is not None:
widget.deleteLater()
i -= 1
def add_table(self, rela, rname):
wtable = custom_table.Table()
# Model
model = QStandardItemModel()
wtable.setModel(model)
model.setHorizontalHeaderLabels(rela.header)
for data in rela.content:
nrow = model.rowCount()
# wtable.insertRow(nrow)
for col, text in enumerate(data):
item = QStandardItem(text)
item.setFlags(item.flags() & ~Qt.ItemIsEditable)
model.setItem(nrow, col, item)
index = self._stack_tables.addWidget(wtable)
self._stack_tables.setCurrentIndex(index)
self._result_list.add_item(rname, rela.count())
示例9: CentralWidget
# 需要导入模块: from PyQt5.QtWidgets import QStackedWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QStackedWidget import count [as 别名]
#.........这里部分代码省略.........
self.recent_databases = filename
self.created = True
def open_query(self):
filter_ = settings.SUPPORTED_FILES.split(';;')[1]
filename, _ = QFileDialog.getOpenFileName(self,
self.tr("Open Query"),
os.path.expanduser("~"),
filter_)
if not filename:
return
# FIXME: mejorar éste y new_query
self.new_query(filename)
def save_query(self, editor=None):
db = self.get_active_db()
fname = db.save_query(editor)
if fname:
self.querySaved.emit(self.tr("Query saved: {}".format(fname)))
def save_query_as(self):
pass
def __sanitize_data(self, data):
"""
This function converts the data into a dictionary
for better handling then.
The argument 'data' is the content of the database.
"""
# FIXME: controlar cuando al final de la línea hay una coma
data_dict = {'tables': []}
for line_count, line in enumerate(data.splitlines()):
# Ignore blank lines
if not line:
continue
if line.startswith('@'):
# This line is a header
tpoint = line.find(':')
if tpoint == -1:
raise Exception("Invalid syntax at line {}".format(
line_count + 1))
table_name, line = line.split(':')
table_name = table_name[1:].strip()
table_dict = {}
table_dict['name'] = table_name
table_dict['header'] = line.split(',')
table_dict['tuples'] = []
else:
for l in csv.reader([line]):
# Remove spaces
l = list(map(str.strip, l))
# FIXME: this is necesary?
if table_dict['name'] == table_name:
table_dict['tuples'].append(l)
if not table_dict['tuples']:
data_dict['tables'].append(table_dict)
return data_dict
def remove_last_widget(self):
""" Remove last widget from stacked """
示例10: TableWidget
# 需要导入模块: from PyQt5.QtWidgets import QStackedWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QStackedWidget import count [as 别名]
class TableWidget(QWidget):
def __init__(self):
super(TableWidget, self).__init__()
vbox = QVBoxLayout(self)
vbox.setContentsMargins(0, 0, 0, 0)
self.relations = {}
# Stack
self.stacked = QStackedWidget()
vbox.addWidget(self.stacked)
def count(self):
return self.stacked.count()
def remove_table(self, index):
widget = self.stacked.widget(index)
self.stacked.removeWidget(widget)
del widget
def current_table(self):
return self.stacked.currentWidget()
def remove_relation(self, name):
del self.relations[name]
def add_relation(self, name, rela):
if self.relations.get(name, None) is None:
self.relations[name] = rela
return True
return False
def update_table(self, data):
current_table = self.current_table()
model = current_table.model()
# Clear content
model.clear()
# Add new header and content
model.setHorizontalHeaderLabels(data.header)
for row_count, row in enumerate(data.content):
for col_count, data in enumerate(row):
item = QStandardItem(data)
item.setFlags(item.flags() & ~Qt.ItemIsEditable)
# item.setSelectable(False)
model.setItem(row_count, col_count, item)
def add_table(self, rela, name):
""" Add new table from New Relation Dialog """
# Create table
table = self.create_table(rela)
self.add_relation(name, rela)
self.stacked.addWidget(table)
def create_table(self, rela):
table = custom_table.Table()
model = QStandardItemModel()
table.setModel(model)
model.setHorizontalHeaderLabels(rela.header)
for row_count, row in enumerate(rela.content):
for col_count, data in enumerate(row):
item = QStandardItem(data)
item.setFlags(item.flags() & ~Qt.ItemIsEditable)
model.setItem(row_count, col_count, item)
return table
示例11: PreferencesDialog
# 需要导入模块: from PyQt5.QtWidgets import QStackedWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QStackedWidget import count [as 别名]
class PreferencesDialog(QDialog):
def __init__(self, mainwindow):
super(PreferencesDialog, self).__init__(mainwindow)
self.setWindowModality(Qt.WindowModal)
if mainwindow:
self.addAction(mainwindow.actionCollection.help_whatsthis)
layout = QVBoxLayout()
layout.setSpacing(10)
self.setLayout(layout)
# listview to the left, stacked widget to the right
top = QHBoxLayout()
layout.addLayout(top)
self.pagelist = QListWidget(self)
self.stack = QStackedWidget(self)
top.addWidget(self.pagelist, 0)
top.addWidget(self.stack, 2)
layout.addWidget(widgets.Separator(self))
b = self.buttons = QDialogButtonBox(self)
b.setStandardButtons(
QDialogButtonBox.Ok
| QDialogButtonBox.Cancel
| QDialogButtonBox.Apply
| QDialogButtonBox.Reset
| QDialogButtonBox.Help)
layout.addWidget(b)
b.accepted.connect(self.accept)
b.rejected.connect(self.reject)
b.button(QDialogButtonBox.Apply).clicked.connect(self.saveSettings)
b.button(QDialogButtonBox.Reset).clicked.connect(self.loadSettings)
b.button(QDialogButtonBox.Help).clicked.connect(self.showHelp)
b.button(QDialogButtonBox.Help).setShortcut(QKeySequence.HelpContents)
b.button(QDialogButtonBox.Apply).setEnabled(False)
# fill the pagelist
self.pagelist.setIconSize(QSize(32, 32))
self.pagelist.setSpacing(2)
for item in pageorder():
self.pagelist.addItem(item())
self.pagelist.currentItemChanged.connect(self.slotCurrentItemChanged)
app.translateUI(self, 100)
# read our size and selected page
qutil.saveDialogSize(self, "preferences/dialog/size", QSize(500, 300))
self.pagelist.setCurrentRow(_prefsindex)
def translateUI(self):
self.pagelist.setFixedWidth(self.pagelist.sizeHintForColumn(0) + 12)
self.setWindowTitle(app.caption(_("Preferences")))
def done(self, result):
if result and self.buttons.button(QDialogButtonBox.Apply).isEnabled():
self.saveSettings()
# save our size and selected page
global _prefsindex
_prefsindex = self.pagelist.currentRow()
super(PreferencesDialog, self).done(result)
def pages(self):
"""Yields the settings pages that are already instantiated."""
for n in range(self.stack.count()):
yield self.stack.widget(n)
def showHelp(self):
userguide.show(self.pagelist.currentItem().help)
def loadSettings(self):
"""Loads the settings on reset."""
for page in self.pages():
page.loadSettings()
page.hasChanges = False
self.buttons.button(QDialogButtonBox.Apply).setEnabled(False)
def saveSettings(self):
"""Saves the settings and applies them."""
for page in self.pages():
if page.hasChanges:
page.saveSettings()
page.hasChanges = False
self.buttons.button(QDialogButtonBox.Apply).setEnabled(False)
# emit the signal
app.settingsChanged()
def slotCurrentItemChanged(self, item):
item.activate()
def changed(self):
"""Call this to enable the Apply button."""
self.buttons.button(QDialogButtonBox.Apply).setEnabled(True)