本文整理汇总了Python中PyQt5.QtWidgets.QListView.setModel方法的典型用法代码示例。如果您正苦于以下问题:Python QListView.setModel方法的具体用法?Python QListView.setModel怎么用?Python QListView.setModel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QListView
的用法示例。
在下文中一共展示了QListView.setModel方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from PyQt5.QtWidgets import QListView [as 别名]
# 或者: from PyQt5.QtWidgets.QListView import setModel [as 别名]
def __init__(self, *args):
QWidget.__init__(self, *args)
# create table
list_data = [1,2,3,4]
lm = MyListModel(list_data, self)
lv = QListView()
lv.setModel(lm)
# layout
layout = QVBoxLayout()
layout.addWidget(lv)
self.setLayout(layout)
示例2: main
# 需要导入模块: from PyQt5.QtWidgets import QListView [as 别名]
# 或者: from PyQt5.QtWidgets.QListView import setModel [as 别名]
def main(args):
app = QApplication(args)
page = QSplitter()
data = Model(1000, 10, page)
selections = QItemSelectionModel(data)
table = QTableView()
table.setModel(data)
table.setSelectionModel(selections)
table.horizontalHeader().setSectionsMovable(True)
table.verticalHeader().setSectionsMovable(True)
# Set StaticContents to enable minimal repaints on resizes.
table.viewport().setAttribute(Qt.WA_StaticContents)
page.addWidget(table)
tree = QTreeView()
tree.setModel(data)
tree.setSelectionModel(selections)
tree.setUniformRowHeights(True)
tree.header().setStretchLastSection(False)
tree.viewport().setAttribute(Qt.WA_StaticContents)
# Disable the focus rect to get minimal repaints when scrolling on Mac.
tree.setAttribute(Qt.WA_MacShowFocusRect, False)
page.addWidget(tree)
list = QListView()
list.setModel(data)
list.setSelectionModel(selections)
list.setViewMode(QListView.IconMode)
list.setSelectionMode(QAbstractItemView.ExtendedSelection)
list.setAlternatingRowColors(False)
list.viewport().setAttribute(Qt.WA_StaticContents)
list.setAttribute(Qt.WA_MacShowFocusRect, False)
page.addWidget(list)
page.setWindowIcon(QIcon(images_dir + '/interview.png'))
page.setWindowTitle("Interview")
page.show()
return app.exec_()
示例3: __init__
# 需要导入模块: from PyQt5.QtWidgets import QListView [as 别名]
# 或者: from PyQt5.QtWidgets.QListView import setModel [as 别名]
def __init__(self, parent=None):
super(Window, self).__init__(parent)
model = FileListModel(self)
model.setDirPath(QLibraryInfo.location(QLibraryInfo.PrefixPath))
label = QLabel("Directory")
lineEdit = QLineEdit()
label.setBuddy(lineEdit)
view = QListView()
view.setModel(model)
self.logViewer = QTextBrowser()
self.logViewer.setSizePolicy(QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred))
lineEdit.textChanged.connect(model.setDirPath)
lineEdit.textChanged.connect(self.logViewer.clear)
model.numberPopulated.connect(self.updateLog)
layout = QGridLayout()
layout.addWidget(label, 0, 0)
layout.addWidget(lineEdit, 0, 1)
layout.addWidget(view, 1, 0, 1, 2)
layout.addWidget(self.logViewer, 2, 0, 1, 2)
self.setLayout(layout)
self.setWindowTitle("Fetch More Example")
示例4: SettingWindow
# 需要导入模块: from PyQt5.QtWidgets import QListView [as 别名]
# 或者: from PyQt5.QtWidgets.QListView import setModel [as 别名]
class SettingWindow(QWidget):
# on_addButtonClicked=pyqtSignal()
# on_removeButtonClicked=pyqtSignal()
# on_okButtonClicked=pyqtSignal()
finished=pyqtSignal()
def __init__(self):
QWidget.__init__(self)
self.listview=QListView(self)
self.addButton=QPushButton(self)
self.removeButton=QPushButton(self)
self.resize(630,440)
self.okButton=QPushButton(self)
self.listview.setGeometry(30,30,410,351)
self.addButton.setGeometry(490,40,80,22)
self.addButton.setText("add")
self.addButton.clicked.connect(self.click_add)
self.removeButton.setGeometry(490,80,80,22)
self.removeButton.setText("remove")
self.removeButton.clicked.connect(self.click_remove)
self.okButton.setGeometry(490,150,80,22)
self.okButton.setText("ok")
self.okButton.clicked.connect(self.click_ok)
# self.aw=null
self.fresh()
def click_ok(self):
self.finished.emit()
self.close()
def click_add(self):
self.aw=AddWindow()
self.aw.show()
self.aw.okSig.connect(self.fresh)
def click_remove(self):
self.remove()
def fresh(self):
confFile=open("conf","r")
self.listModel=QStandardItemModel()
self.itemList=cPickle.load(confFile)
confFile.close()
for item in self.itemList:
itemView=QStandardItem(QIcon(item.path),item.name)
itemView.setEditable(False)
self.listModel.appendRow(itemView)
self.listview.setModel(self.listModel)
def remove(self):
index=self.listview.currentIndex().row()
self.itemList.pop(index)
self.listModel.removeRow(index)
confFile=open("conf","w")
cPickle.dump(self.itemList,confFile)
confFile.close()
示例5: QueryDialog
# 需要导入模块: from PyQt5.QtWidgets import QListView [as 别名]
# 或者: from PyQt5.QtWidgets.QListView import setModel [as 别名]
class QueryDialog(QDialog):
"""a dialog to choose an item from a query
"""
choice = pyqtSignal(str)
def __init__(self, query):
super().__init__()
self.query = query
self.create_model()
self.init_UI()
def create_model(self):
"""creates the model as QSqlQueryModel,
using the given query
"""
self.model = QSqlQueryModel()
q = QSqlQuery()
q.exec_(self.query)
self.model.setQuery(q)
def init_UI(self):
"""setup the UI
"""
layout = QVBoxLayout()
self.setLayout(layout)
self.resize(200,200)
self.title = "Choose an existing project"
self.list = QListView(self)
layout.addWidget(self.list)
self.list.setModel(self.model)
self.list.setWhatsThis("Choose a project by clicking on it")
self.btn = QPushButton("Accept", self)
layout.addWidget(self.btn)
self.btn.clicked.connect(self.on_btn_clicked)
self.btn.setWhatsThis("Click here to accept your selection (works only if a project has been selected)")
def on_btn_clicked(self):
"""when self.btn is clicked, accept the choice and emit it as self.choice
"""
selected = self.list.selectedIndexes()
if selected:
index = selected[0]
chosen = self.model.data(index, Qt.DisplayRole)
self.choice.emit(chosen)
self.close()
self.choice.emit("")
self.close()
示例6: initUI
# 需要导入模块: from PyQt5.QtWidgets import QListView [as 别名]
# 或者: from PyQt5.QtWidgets.QListView import setModel [as 别名]
def initUI(self):
#GrBox1
GrBox=QGroupBox()
vbox = QHBoxLayout(self)
vbox.setContentsMargins(0,0,0,0)
#GrBox.setFixedHeight(60)
pathButton = QPushButton(QIcon('icons\\pack.png'),"Папка")
pathButton.setIconSize(QSize(25,25))
pathButton.setVisible(True)
pathLable=QLineEdit()
#pathLable.setReadOnly(True)
subPathCheck=QCheckBox()
subPathCheck.setText("Подпапки")
subPathCheck.setCheckState(0)
vbox.addWidget(pathLable)
vbox.addWidget(subPathCheck)
vbox.addWidget(pathButton)
GrBox.setLayout(vbox)
#/GrBox1
#FilesTable
FilesTable=QListView(self)
FilesTable.setToolTip("Список файлов, выберите нужные файлы для обработки,\nдля просмотра файла дважды щелкните по нему")
FilesTableModel = QStandardItemModel()
FilesTable.setModel(FilesTableModel)
#/FilesTable
#mainLayout
mainLayout = QVBoxLayout()
mainLayout.setContentsMargins(0,0,0,0)
mainLayout.setMenuBar(GrBox)
mainLayout.addWidget(FilesTable)
#/mainLayout
#self
self.setLayout(mainLayout)
self.path=pathLable.text()
self.pathLable=pathLable
self.subPathCheck=subPathCheck
self.FilesTableModel = FilesTableModel
#/self
#connections
pathLable.textChanged.connect(self.setPath)
pathButton.clicked.connect(self.selectPath)
subPathCheck.clicked.connect(self.setPath)
FilesTableModel.itemChanged.connect(self.ChangeFilesList)
FilesTable.doubleClicked.connect(self.openFile)
示例7: ListScrollArea
# 需要导入模块: from PyQt5.QtWidgets import QListView [as 别名]
# 或者: from PyQt5.QtWidgets.QListView import setModel [as 别名]
class ListScrollArea(QVBoxLayout):
def __init__(self, parent):
QVBoxLayout.__init__(self, parent)
self.scroll_area = QScrollArea()
# A ListView is a widget, instead of a layout, so there should be no need for additional containers
self.list_view = QListView()
self.scroll_area.setWidget(self.list_view)
self.addWidget(self.list_view)
self.view_model = QStringListModel()
self.list_view.setModel(self.view_model)
def add_item_by_string(self, value):
current_values = self.view_model.stringList()
if value not in current_values:
current_values.append(value)
self.view_model.setStringList(current_values)
def remove_item_by_string(self, value):
current_values = self.view_model.stringList()
if value in current_values:
current_values.remove(value)
self.view_model.setStringList(current_values)
def clear_all(self):
self.view_model.setStringList([])
def get_currently_selected_item(self):
currently_selected_item_index = self.view_model.currentIndex()
currently_selected_item_text = str(self.list_view.data(currently_selected_item_index))
return currently_selected_item_text
def get_item(self, index):
current_values = self.view_model.stringList()
if index < len(current_values):
return current_values[index]
return None
def get_num_items(self):
return len(self.view_model.stringList())
示例8: MDIHistory
# 需要导入模块: from PyQt5.QtWidgets import QListView [as 别名]
# 或者: from PyQt5.QtWidgets.QListView import setModel [as 别名]
class MDIHistory(QWidget, _HalWidgetBase):
def __init__(self, parent=None):
super(MDIHistory, self).__init__(parent)
self.setMinimumSize(QSize(200, 150))
self.setWindowTitle("PyQt5 editor test example")
lay = QVBoxLayout()
lay.setContentsMargins(0,0,0,0)
self.setLayout(lay)
self.list = QListView()
self.list.setEditTriggers(QListView.NoEditTriggers)
self.list.activated.connect(self.activated)
self.list.setAlternatingRowColors(True)
self.list.selectionChanged = self.selectionChanged
self.model = QStandardItemModel(self.list)
self.MDILine = MDILine()
self.MDILine.soft_keyboard = False
self.MDILine.line_up = self.line_up
self.MDILine.line_down = self.line_down
STATUS.connect('reload-mdi-history', self.reload)
# add widgets
lay.addWidget(self.list)
lay.addWidget(self.MDILine)
self.fp = os.path.expanduser(INFO.MDI_HISTORY_PATH)
try:
open(self.fp, 'r')
except:
open(self.fp, 'a+')
LOG.debug('MDI History file created: {}'.format(self.fp))
self.reload()
self.select_row('last')
def _hal_init(self):
STATUS.connect('state-off', lambda w: self.setEnabled(False))
STATUS.connect('state-estop', lambda w: self.setEnabled(False))
STATUS.connect('interp-idle', lambda w: self.setEnabled(STATUS.machine_is_on()
and (STATUS.is_all_homed()
or INFO.NO_HOME_REQUIRED)))
STATUS.connect('interp-run', lambda w: self.setEnabled(not STATUS.is_auto_mode()))
STATUS.connect('all-homed', lambda w: self.setEnabled(STATUS.machine_is_on()))
def reload(self, w=None ):
self.model.clear()
try:
with open(self.fp,'r') as inputfile:
for line in inputfile:
line = line.rstrip('\n')
item = QStandardItem(line)
self.model.appendRow(item)
self.list.setModel(self.model)
self.list.scrollToBottom()
if self.MDILine.hasFocus():
self.select_row('last')
except:
LOG.debug('File path is not valid: {}'.format(fp))
def selectionChanged(self,old, new):
cmd = self.getSelected()
self.MDILine.setText(cmd)
selectionModel = self.list.selectionModel()
if selectionModel.hasSelection():
self.row = selectionModel.currentIndex().row()
def getSelected(self):
selected_indexes = self.list.selectedIndexes()
selected_rows = [item.row() for item in selected_indexes]
# iterates each selected row in descending order
for selected_row in sorted(selected_rows, reverse=True):
text = self.model.item(selected_row).text()
return text
def activated(self):
cmd = self.getSelected()
self.MDILine.setText(cmd)
self.MDILine.submit()
self.select_row('down')
def select_row(self, style):
selectionModel = self.list.selectionModel()
parent = QModelIndex()
self.rows = self.model.rowCount(parent) - 1
if style == 'last':
self.row = self.rows
elif style == 'up':
if self.row > 0:
self.row -= 1
else:
self.row = self.rows
elif style == 'down':
if self.row < self.rows:
self.row += 1
else:
self.row = 0
else:
return
#.........这里部分代码省略.........
示例9: ConfigurationView
# 需要导入模块: from PyQt5.QtWidgets import QListView [as 别名]
# 或者: from PyQt5.QtWidgets.QListView import setModel [as 别名]
class ConfigurationView(QWidget):
"""
Displays the configuration view.
"""
def __init__(self, parent=None):
super(ConfigurationView, self).__init__(parent)
self._layout = QBoxLayout(QBoxLayout.TopToBottom)
self.setLayout(self._layout)
self._editView = EditView(parent)
# initialize list view
self._listView = QListView()
self._configuration_model = self._get_config_model()
self._listView.setModel(self._configuration_model)
# initialize detail view
self._detailView = QWidget()
self._detailLayout = QBoxLayout(QBoxLayout.TopToBottom)
self._detailView.setLayout(self._detailLayout)
self._detailPanels = {}
self._currentDetailPanel = None
self._currentConfiguration = None # type: Configuration
self._config_wide_print_amounts = {}
self._recalculateEffectivePrintAmounts = False
# add widgets to layout
self._layout.addWidget(QLabel("List of Configurations"))
self._layout.addWidget(self._listView)
self._layout.addWidget(self._detailView)
self._create_detail_view()
# hide detail view on start
self._detailView.hide()
# selected configs map
self._selected_configs = {}
self._selected_counter = 0
# add event listener for selection change
self._listView.clicked.connect(self._on_selection_change)
self._listView.selectionModel().currentChanged.connect(self._on_selection_change)
def add_configuration(self, configuration):
"""
Adds the given configuration to the list view and opens the edit view.
:param configuration:
:type configuration: Configuration
"""
item = create_new_list_item(configuration.get_name())
self._configuration_model.appendRow(item)
self._editView.show_for_configuration(configuration)
def select_first_item(self):
rect = QRect(0,0,1,1)
self._listView.setSelection(rect, QItemSelectionModel.Select)
def update_model(self):
self._configuration_model = self._get_config_model()
self._listView.setModel(self._configuration_model)
@staticmethod
def _get_config_model():
data = DataStorage()
configurations_order = data.get_configurations_order()
model = QStandardItemModel()
for name in configurations_order:
item = create_new_list_item(name)
model.appendRow(item)
return model
def _on_selection_change(self, model_index):
"""
Called on selecting a new item in the listView.
:param model_index: index of selected item
:type model_index: QModelIndex
"""
data = DataStorage()
configurations = data.get_configurations()
selected_item = self._configuration_model.itemFromIndex(model_index) # type: QStandardItem
current_config_name = selected_item.text()
current_config = configurations[current_config_name] # type: Configuration
self._show_detail_view(current_config)
config_wide_print_amount = self._config_wide_print_amounts[current_config_name]
material_print_amounts = current_config.get_effective_material_print_amounts(
config_wide_print_amount,
self._recalculateEffectivePrintAmounts
)
self._recalculateEffectivePrintAmounts = False
if self._selected_counter == 0:
MaterialView.reset_check_state_and_print_amount()
for material in current_config.get_materials():
item = get_item(MaterialView.get_model().invisibleRootItem(), material.get_name())
if item is not None:
print_amount = material_print_amounts[material.get_name()]
if is_checked(selected_item):
check_item(item)
#.........这里部分代码省略.........
示例10: FlickrViewer
# 需要导入模块: from PyQt5.QtWidgets import QListView [as 别名]
# 或者: from PyQt5.QtWidgets.QListView import setModel [as 别名]
class FlickrViewer(QMainWindow):
def __init__(self):
super(FlickrViewer, self).__init__()
self.logged_in = False
self.scaleFactor = 0.0
self.photos = []
self.current_page = 1
self.topLayout = QGridLayout()
self.central = QWidget()
self.central.setLayout(self.topLayout)
self.setCentralWidget(self.central)
self.picture_list = QListView()
self.photos_model = QStandardItemModel(self.picture_list)
self.topLayout.addWidget(self.picture_list,0,0)
self.picture_list.setModel(self.photos_model)
self.picture_list.clicked.connect(self.on_item_selected)
self.detail = QWidget()
self.detail_layout = QVBoxLayout()
self.detail_thumb = QLabel()
self.detail.setLayout(self.detail_layout)
self.detail_title = QLabel("Photo Title:")
self.detail_embedding = QPlainTextEdit("..")
self.detail_layout.addWidget(self.detail_thumb)
self.detail_layout.addWidget(self.detail_title)
self.detail_layout.addWidget(self.detail_embedding)
self.topLayout.addWidget(self.detail,0,1)
self.createActions()
self.createMenus()
self.setWindowTitle("Flickr Viewer")
self.resize(500, 400)
def login(self):
self.flickr = flick.Flick()
self.logged_in = True
#if self.flickr.flickr_connect():
# codebox, ok = QInputDialog.getText(self,"Input Flickr Code","Code", QLineEdit.Normal, "")
# if ok:
# self.flickr.verify(str(codebox))
# else:
# return
def getPhotos(self):
if not self.logged_in:
self.login()
photos = []
tphotos = []
bar = QProgressDialog("Getting Photos", "Stop", 0, 10)
bar.setWindowTitle("Downloading from Flickr")
bar.setWindowModality(Qt.WindowModal)
bar.setValue(0)
photos = self.flickr.get_recent_photos(self.current_page)
bar.show()
if DEBUG:
print(photos)
prg = 0
for pid, title in photos:
if bar.wasCanceled():
return
turl = self.flickr.get_thumbnail_url(pid)
murl = self.flickr.get_medium_url(pid)
lurl = self.flickr.get_link_url(pid)
if DEBUG: print(turl)
p = Photo()
p.thumb_url = turl
p.medium_url = murl
p.link = lurl
p.thumb = urllib.request.urlopen(turl).read()
p.title = title
tphotos.append(p)
prg += 1
bar.setValue(prg)
self.current_page += 1
for p in tphotos:
self.photos.append(p)
item = QStandardItem()
item.setText(p.title)
self.photos_model.appendRow(item)
def gen_markdown(self,photo):
md = "<div class=\"media\" markdown=\"1\">\n" + \
"<a href=\"" + photo.link + "\"><img src=\"" + photo.medium_url + "\" alt=\"" + photo.title + "\" class=\"img-fluid\"/></a>\n" + \
"<div class=\"media-body\" markdown=\"1\">\n" + \
#.........这里部分代码省略.........
示例11: OS2Tab
# 需要导入模块: from PyQt5.QtWidgets import QListView [as 别名]
# 或者: from PyQt5.QtWidgets.QListView import setModel [as 别名]
class OS2Tab(TabWidget):
def __init__(self, font, parent=None):
super().__init__(parent, name="OS/2")
# OS2Group = QGroupBox("OS/2 table", self)
# OS2Group.setFlat(True)
OS2Layout = QGridLayout(self)
usWidthClassLabel = QLabel("usWidthClass:", self)
self.usWidthClassDrop = QComboBox(self)
items = [
"None", "Ultra-condensed", "Extra-condensed", "Condensed",
"Semi-Condensed", "Medium (normal)", "Semi-expanded", "Expanded",
"Extra-expanded", "Ultra-expanded"]
self.usWidthClassDrop.insertItems(0, items)
if font.info.openTypeOS2WidthClass is not None:
self.usWidthClassDrop.setCurrentIndex(
font.info.openTypeOS2WidthClass)
fsSelectionLabel = QLabel("fsSelection:", self)
fsSelection = font.info.openTypeOS2Selection
self.fsSelectionList = QListView(self)
items = [
"1 UNDERSCORE", "2 NEGATIVE", "3 OUTLINED", "4 STRIKEOUT",
"7 USE_TYPO_METRICS", "8 WWS", "9 OBLIQUE"]
# http://stackoverflow.com/a/26613163
model = QStandardItemModel(7, 1)
for index, elem in enumerate(items):
item = QStandardItem()
item.setText(elem)
item.setCheckable(True)
bit = index + 1
if fsSelection is not None and bit in fsSelection:
# maybe default setting? if so, unneeded
item.setCheckState(Qt.Checked)
else:
item.setCheckState(Qt.Unchecked)
model.setItem(index, item)
self.fsSelectionList.setModel(model)
achVendorIDLabel = QLabel("achVendorID:", self)
self.achVendorIDEdit = QLineEdit(font.info.openTypeOS2VendorID, self)
self.achVendorIDEdit.setMaxLength(4)
fsTypeLabel = QLabel("fsType:", self)
fsType = font.info.openTypeOS2Type
self.fsTypeDrop = QComboBox(self)
items = [
"No embedding restrictions", "Restricted embedding",
"Preview and print embedding allowed",
"Editable embedding allowed"]
self.allowSubsettingBox = QCheckBox("Allow subsetting", self)
self.allowBitmapEmbeddingBox = QCheckBox(
"Allow only bitmap embedding", self)
self.fsTypeDrop.currentIndexChanged[int].connect(
self._updateFsTypeVisibility)
self.fsTypeDrop.insertItems(0, items)
if fsType is not None:
for i in range(1, 4):
if i in fsType:
self.fsTypeDrop.setCurrentIndex(i)
break
self.allowSubsettingBox.setChecked(8 not in fsType)
self.allowBitmapEmbeddingBox.setChecked(9 in fsType)
# XXX: ulUnicodeRange
# XXX: ulCodePageRange
sTypoAscenderLabel = QLabel("sTypoAscender:", self)
sTypoDescenderLabel = QLabel("sTypoDescender:", self)
sTypoLineGapLabel = QLabel("sTypoLineGap:", self)
usWeightClassLabel = QLabel("usWeightClass:", self)
usWinAscentLabel = QLabel("usWinAscent:", self)
usWinDescentLabel = QLabel("usWinDescent:", self)
ySubscriptXSizeLabel = QLabel("ySubscriptXSize:", self)
ySubscriptYSizeLabel = QLabel("ySubscriptYSize:", self)
ySubscriptXOffsetLabel = QLabel("ySubscriptXOffset:", self)
ySubscriptYOffsetLabel = QLabel("ySubscriptYOffset:", self)
ySuperscriptXSizeLabel = QLabel("ySuperscriptXSize:", self)
ySuperscriptYSizeLabel = QLabel("ySuperscriptYSize:", self)
ySuperscriptXOffsetLabel = QLabel("ySuperscriptXOffset:", self)
ySuperscriptYOffsetLabel = QLabel("ySuperscriptYOffset:", self)
yStrikeoutSizeLabel = QLabel("yStrikeoutSize:", self)
yStrikeoutPositionLabel = QLabel("yStrikeoutPosition:", self)
self.loadPositiveInteger(
font, "openTypeOS2WeightClass", "usWeightClass")
self.loadInteger(font, "openTypeOS2TypoAscender", "sTypoAscender")
self.loadInteger(font, "openTypeOS2TypoDescender", "sTypoDescender")
self.loadInteger(font, "openTypeOS2TypoLineGap", "sTypoLineGap")
self.loadPositiveInteger(font, "openTypeOS2WinAscent", "usWinAscent")
self.loadPositiveInteger(font, "openTypeOS2WinDescent", "usWinDescent")
self.loadInteger(font, "openTypeOS2SubscriptXSize", "ySubscriptXSize")
self.loadInteger(font, "openTypeOS2SubscriptYSize", "ySubscriptYSize")
self.loadInteger(
font, "openTypeOS2SubscriptXOffset", "ySubscriptXOffset")
self.loadInteger(
font, "openTypeOS2SubscriptYOffset", "ySubscriptYOffset")
self.loadInteger(
#.........这里部分代码省略.........
示例12: DesktopIconWidget
# 需要导入模块: from PyQt5.QtWidgets import QListView [as 别名]
# 或者: from PyQt5.QtWidgets.QListView import setModel [as 别名]
class DesktopIconWidget(QFrame):
def __init__(self, parent):
QFrame.__init__(self, parent)
self.setFrameStyle(QFrame.Box | QFrame.Sunken)
self.setStyleSheet("QListView{background:transparent;}")
self.listView = QListView(self)
self.setLayout(QHBoxLayout())
self.layout().setContentsMargins(0, 0, 0, 0)
self.layout().addWidget(self.listView)
self.listView.setContextMenuPolicy(Qt.CustomContextMenu)
self.listView.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.listView.setMovement(QListView.Snap)
self.listView.setFlow(QListView.LeftToRight)
self.listView.setResizeMode(QListView.Adjust)
self.listView.setGridSize(QSize(self.logicalDpiX() / 96 * 70,
self.logicalDpiY() / 96 * 70))
self.listView.setViewMode(QListView.IconMode)
self.quickDesktopModel = QuickDesktopModel(self.window().platform.databaseFile)
self.listView.setModel(self.quickDesktopModel)
self.createActions()
self.makeConnections()
def createActions(self):
self.actionCreateComputer = QAction(self.tr("我的电脑(&C)"), self)
self.actionCreateDocuments = QAction(self.tr("我的文档(&D)"), self)
self.actionCreateMusic = QAction(self.tr("我的音乐(&M)"), self)
self.actionCreatePictures = QAction(self.tr("我的图片(&P)"), self)
self.actionCreateShortcut = QAction(self.tr("创建快捷方式(&C)"), self)
self.actionCreateShortcut.setIcon(QIcon(":/images/new.png"))
self.actionCreateBookmark = QAction(self.tr("创建网络链接(&B)"), self)
self.actionCreateBookmark.setIcon(QIcon(":/images/insert-link.png"))
self.actionRemoveShortcut = QAction(self.tr("删除快捷方式(&R)"), self)
self.actionRemoveShortcut.setIcon(QIcon(":/images/delete.png"))
self.actionRenameShortcut = QAction(self.tr("重命名(&N)"), self)
self.actionRenameShortcut.setIcon(QIcon(":/images/edit-rename.png"))
self.actionEditShortcut = QAction(self.tr("编辑快捷方式(&E)"), self)
self.actionEditShortcut.setIcon(QIcon(":/images/edit.png"))
def makeConnections(self):
self.listView.customContextMenuRequested.connect(self.onQuickDesktopContextMenuRequest)
self.listView.activated.connect(self.runQuickDesktopShortcut)
self.actionCreateComputer.triggered.connect(self.createComputerShortcut)
self.actionCreateDocuments.triggered.connect(self.createDocumentsShortcut)
self.actionCreateMusic.triggered.connect(self.createMusicShortcut)
self.actionCreatePictures.triggered.connect(self.createPicturesShortcut)
self.actionCreateShortcut.triggered.connect(self.createShortcut)
self.actionCreateBookmark.triggered.connect(self.createBookmark)
self.actionEditShortcut.triggered.connect(self.editShortcut)
self.actionRemoveShortcut.triggered.connect(self.removeShortcut)
self.actionRenameShortcut.triggered.connect(self.renameShortcut)
def onQuickDesktopContextMenuRequest(self, pos):
index = self.listView.indexAt(pos)
self.listView.setCurrentIndex(index)
menu = QMenu()
menu.addAction(self.actionCreateShortcut)
menu.addAction(self.actionCreateBookmark)
menu2 = menu.addMenu(self.tr("创建特殊快捷方式(&S)"))
if os.name == "nt":
menu2.addAction(self.actionCreateComputer)
menu2.addAction(self.actionCreateDocuments)
menu2.addAction(self.actionCreatePictures)
menu2.addAction(self.actionCreateMusic)
if index.isValid():
menu.addAction(self.actionRemoveShortcut)
if not self.quickDesktopModel.isSpecialShortcut(index):
menu.addAction(self.actionEditShortcut)
menu.addAction(self.actionRenameShortcut)
try:
getattr(menu, "exec")(QCursor.pos())
except AttributeError:
getattr(menu, "exec_")(QCursor.pos())
def createShortcut(self):
d = ShortcutDialog(self)
if self.window().runDialog(d.create) == QDialog.Accepted:
shortcut = d.getResult()
shortcut["id"] = str(uuid.uuid4())
self.quickDesktopModel.addShortcut(shortcut)
d.deleteLater()
def createBookmark(self):
d = BookmarkDialog(self)
if self.window().runDialog(d.create) == QDialog.Accepted:
shortcut = {
"id": str(uuid.uuid4()),
"icon": "",
"openwith": "",
"dir": "",
}
shortcut.update(d.getResult())
self.quickDesktopModel.addShortcut(shortcut)
d.deleteLater()
def createComputerShortcut(self):
shortcut = {
#.........这里部分代码省略.........
示例13: keepColumn
# 需要导入模块: from PyQt5.QtWidgets import QListView [as 别名]
# 或者: from PyQt5.QtWidgets.QListView import setModel [as 别名]
class keepColumn(QDialog):
def __init__(self, parent=None):
self.parent = parent
self.parent.statusbar.showMessage("Keep Columns started...")
QWidget.__init__(self,parent)
self.ui = gui.keepColumnUi()
self.ui.setupUi(self)
self.columns = []
self.batch_files = filedialog.askopenfilenames(parent=root, title='Choose the file(s) you want to modify')
if len(self.batch_files) == 0:
self.close()
return
self.parent.statusbar.showMessage("Checking column validity...")
#extract columns
for item in self.batch_files:
self.columns.append(helpers.extract_columns(item))
#check to see if all columns are equal in all the datasets
if not helpers.are_columns_same(self.columns):
if not helpers.columns_not_equal_message(self):
self.close()
return
#list of items to check from
self.model = QStandardItemModel()
try:
for col in self.columns[0]:
item = QStandardItem(col)
item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
item.setData(QVariant(Qt.Unchecked), Qt.CheckStateRole)
self.model.appendRow(item)
except IndexError:
pass
self.list = QListView(self)
self.list.setModel(self.model)
self.list.setGeometry(10, 60, 380, 430)
self.ui.removeBtn.clicked.connect(self.keep)
self.ui.closeBtn.clicked.connect(self.close)
self.parent.statusbar.showMessage("Welcome back!")
self.show()
def close(self):
self.parent.statusbar.showMessage("Welcome back!")
self.parent.ui.logOutput.append("")
self.done(55)
def keep(self):
self.parent.statusbar.showMessage("Keep Columns in process...")
self.columns_to_keep = []
i = 0
while self.model.item(i):
if self.model.item(i).checkState() == 2:
self.columns_to_keep.append(self.model.item(i).text())
i += 1
query = "Are you sure you want to proceed?"
reply = QMessageBox.question(self, 'Message',query, QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.No:
self.columns_to_keep = []
return
self.parent.statusbar.showMessage("Processing...")
self.parent.ui.logOutput.append("KEPT:")
print("KEPT:")
#per file first retrieve data then filter columnarly
for file in self.batch_files:
list_colindx = []
datablob = helpers.clean_header(file)
for item in self.columns_to_keep:
list_colindx.append(datablob[0].index(item))
for i in range(len(datablob)):
datablob[i][:] = [x for i, x in enumerate(datablob[i]) if i in list_colindx]
split_name = file.split('.')
now = time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
output_file = split_name[0] + "_keep_columns_" + now + "." + split_name[1]
helpers.write_out_to_file(output_file,datablob)
self.parent.ui.logOutput.append(" " + str(file.split('/')[-1]))
print(" " + str(file.split('/')[-1]))
#.........这里部分代码省略.........
示例14: PatchPanel
# 需要导入模块: from PyQt5.QtWidgets import QListView [as 别名]
# 或者: from PyQt5.QtWidgets.QListView import setModel [as 别名]
class PatchPanel(QGroupBox):
"""Group of widget to patch an universe"""
def __init__(self, parent):
super(PatchPanel, self).__init__()
self.ola = parent.ola
self.parent = parent
self.device_selected = None
self.universe = None
grid = QGridLayout()
self.inputs_model = PortList(self, 'input_mode')
self.outputs_model = PortList(self, 'output_mode')
self.devices = QListView()
self.devices_model = DeviceList(self)
self.devices.setModel(self.devices_model)
self.inputs = QListView()
self.inputs.setModel(self.inputs_model)
self.inputs.setMinimumHeight(400)
self.inputs.setMinimumHeight(120)
self.outputs = QListView()
self.outputs.setModel(self.outputs_model)
self.outputs.setMinimumHeight(400)
self.outputs.setMinimumHeight(120)
# Universe Selected Change
self.devices.selectionModel().selectionChanged.connect(self.device_selection_changed)
devices_label = QLabel('Devices')
grid.addWidget(devices_label, 0, 0, 1, 1)
grid.addWidget(self.devices, 1, 0, 21, 1)
inputs_label = QLabel('Inputs')
grid.addWidget(inputs_label, 0, 1, 1, 1)
grid.addWidget(self.inputs, 1, 1, 10, 1)
outputs_label = QLabel('Outputs')
grid.addWidget(outputs_label, 11, 1, 1, 1)
grid.addWidget(self.outputs, 12, 1, 10, 1)
grid.setSpacing(5)
self.setLayout(grid)
def display_ports(self, universe=None):
"""
Request a list of Devices
if universe == None, a list of None-Already-Patched ports is send
"""
if universe is None:
result = self.ola.client.GetCandidatePorts(self.GetCandidatePortsCallback, None)
return result
result = self.ola.client.FetchDevices(self.GetDevicesCallback, 0)
return result
def GetCandidatePortsCallback(self, status, devices):
"""
Called for a new universe
"""
if status.Succeeded():
# clear the list of devices
self.devices_model.devices = []
if debug:
print('found', len(devices), 'candidate devices')
for device in devices:
self.devices_model.devices.append(device)
self.parent.ola.devicesList.emit()
self.refresh_ports()
def GetDevicesCallback(self, status, devices):
"""
Fill-in universe menus with candidate devices/ports
We need to make menus checkable to be able to patch ports
"""
if status.Succeeded():
# clear the list of devices
self.devices_model.devices = []
for device in devices:
if device.input_ports == []:
# there is no input ports
if device.output_ports == []:
# no in + no out = no device
pass
else:
self.devices_model.devices.append(device)
else:
self.devices_model.devices.append(device)
if debug:
print('found', len(self.devices_model.devices), 'devices')
self.parent.ola.devicesList.emit()
self.refresh_ports()
# if there was a selection before, restore it
#if self.device_selected:
#self.devices.setSelection(self.device_selected)
def refresh_ports(self):
device = self.device_selected
if device:
# reset the models of inputs and outputs
self.inputs_model.ports = []
#.........这里部分代码省略.........
示例15: MyModel
# 需要导入模块: from PyQt5.QtWidgets import QListView [as 别名]
# 或者: from PyQt5.QtWidgets.QListView import setModel [as 别名]
class MyModel(QAbstractListModel):
def __init__(self, parent):
super().__init__(parent)
def rowCount(self, parent):
return 10
def data(self, index, role):
if role == Qt.DisplayRole:
return "{}".format(index.row())
return QVariant()
if __name__ == '__main__':
app = QApplication(sys.argv)
list_view = QListView()
my_model = MyModel(None)
list_view.setModel(my_model)
list_view.show()
# The mainloop of the application. The event handling starts from this point.
# The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead.
exit_code = app.exec_()
# The sys.exit() method ensures a clean exit.
# The environment will be informed, how the application ended.
sys.exit(exit_code)