def show_preview_images_into_list(self, img_path): """ adds one or more thumbnail(previews) images to the list """ for img in img_path: icon = QIcon(QPixmap(img)) item = QListWidgetItem(icon, None) item.setToolTip(img) self.ui.listWidget.addItem(item)
def add_item(obj, icon: str = "", text: str = "", tooltip: str = "", selectable: bool = False, select: bool = False, checkable: bool = False, check: bool = False, hide: bool = False, font_size: int = 12, icon_size=(25, 25)): font = QFont() font.setPointSize(font_size) att = QListWidgetItem() att.setText(text) att.setHidden(hide) att.setFont(font) if icon: att.setIcon(icon) if tooltip: att.setToolTip(tooltip) if checkable: att.setCheckState(check) if selectable: att.setSelected(select) obj.setIconSize(QSize(icon_size[0], icon_size[1])) return att
def update_account_feed(self): if self.hist_account is None: return try: updated_feed = self.hist_account.get_account_posts() except: print("could not update feed") return if len(self.feed) == 0: self.feed = updated_feed else: for post in updated_feed[::-1]: found = False for p in self.feed: if post["authorperm"] == p["authorperm"]: found = True if not found: self.feed.insert(0, post) if (addTzInfo(datetime.utcnow()) - post["created"]).total_seconds() / 60 < 5: self.tray.showMessage(post["author"], post["title"]) with self.updateLock: if self.post is None: self.post = self.feed[0] self.triggeredPreview() self.feedListWidget.currentRowChanged.disconnect(self.change_displayed_post) self.feedListWidget.clear() for post in self.feed[::-1]: post_text = "%s - %s" % (post["author"], post["title"]) post_item = QListWidgetItem() post_item.setText(post_text) post_item.setToolTip(post["author"]) self.feedListWidget.insertItem(0, post_item) self.feedListWidget.currentRowChanged.connect(self.change_displayed_post, Qt.QueuedConnection)
def open_media_library(self, index): """Open a directory or file from the media library into an empty playlist.""" self.playlist.clear() self.playlist_view.clear() if self.library_model.fileName(index).endswith(('mp3', 'flac')): self.playlist.addMedia( QMediaContent(QUrl().fromLocalFile( self.library_model.filePath(index)))) self.playlist_view.addItem(self.library_model.fileName(index)) elif self.library_model.isDir(index): directory = self.library_model.filePath(index) for dirpath, __, files in os.walk(directory): for filename in natsort.natsorted(files, alg=natsort.ns.PATH): file = os.path.join(dirpath, filename) if filename.endswith(('mp3', 'flac')): self.playlist.addMedia( QMediaContent(QUrl().fromLocalFile(file))) playlist_item = QListWidgetItem(filename) playlist_item.setToolTip(filename) self.playlist_view.addItem(playlist_item) self.player.setPlaylist(self.playlist) self.player.play()
def __init__(self, workspace, documents): super(_UISaveFiles, self).__init__(workspace) self.cancelled = False uic.loadUi(os.path.join(DATA_FILES_PATH, 'ui/SaveFiles.ui'), self) self.buttonBox.clicked.connect(self._onButtonClicked) self._documents = documents for index, document in enumerate(documents): name = document.fileName() if name is None: name = 'untitled' item = QListWidgetItem(name, self.listWidget) if document.filePath() is not None: item.setToolTip(document.filePath()) item.setCheckState(Qt.Checked) # Retitle buttons, add first letter shortcuts for them. bb = self.buttonBox self._shortcut = (self._firstLetterShortcut(bb.Discard, 'close &Without saving'), self._firstLetterShortcut(bb.Cancel, '&Cancel close'), self._firstLetterShortcut(bb.Save, '&Save checked')) self.buttonBox.button(QDialogButtonBox.Cancel).setFocus()
def initCategories(self): generalButton = QListWidgetItem(self.categories) generalButton.setIcon(QIcon(':/images/settings-general.png')) generalButton.setText('General') generalButton.setToolTip('General settings') generalButton.setTextAlignment(Qt.AlignHCenter) generalButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) videoButton = QListWidgetItem(self.categories) videoButton.setIcon(QIcon(':/images/settings-video.png')) videoButton.setText('Video') videoButton.setToolTip('Video settings') videoButton.setTextAlignment(Qt.AlignHCenter) videoButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) themeButton = QListWidgetItem(self.categories) themeButton.setIcon(QIcon(':/images/settings-theme.png')) themeButton.setText('Theme') themeButton.setToolTip('Theme settings') themeButton.setTextAlignment(Qt.AlignHCenter) themeButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) ffmpegButton = QListWidgetItem(self.categories) ffmpegButton.setIcon(QIcon(':/images/settings-ffmpeg.png')) ffmpegButton.setText('Tools') ffmpegButton.setToolTip('Tools settings') ffmpegButton.setTextAlignment(Qt.AlignHCenter) ffmpegButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) logsButton = QListWidgetItem(self.categories) logsButton.setIcon(QIcon(':/images/settings-logs.png')) logsButton.setText('Logs') logsButton.setToolTip('Logging settings') logsButton.setTextAlignment(Qt.AlignHCenter) logsButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.categories.currentItemChanged.connect(self.changePage) self.categories.setCurrentRow(0) self.categories.setMaximumWidth( self.categories.sizeHintForColumn(0) + 2)
def renderClips(self, cliptimes: list) -> int: self.clear() externalCount = 0 for index, clip in enumerate(cliptimes): chapterName, endItem = '', '' if isinstance(clip[1], QTime): endItem = clip[1].toString(self.parent.timeformat) self.parent.totalRuntime += clip[0].msecsTo(clip[1]) listitem = QListWidgetItem(self) listitem.setToolTip('Drag to reorder clips') if len(clip[3]): listitem.setToolTip(clip[3]) externalCount += 1 if self.parent.createChapters: chapterName = clip[4] if clip[ 4] is not None else 'Chapter {}'.format(index + 1) listitem.setStatusTip( 'Reorder clips with mouse drag & drop or right-click menu on the clip to be moved' ) listitem.setTextAlignment(Qt.AlignVCenter) listitem.setData(Qt.DecorationRole + 1, clip[2]) listitem.setData(Qt.DisplayRole + 1, clip[0].toString(self.parent.timeformat)) listitem.setData(Qt.UserRole + 1, endItem) listitem.setData(Qt.UserRole + 2, clip[3]) listitem.setData(Qt.UserRole + 3, chapterName) listitem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsDragEnabled | Qt.ItemIsEnabled) self.addItem(listitem) if isinstance(clip[1], QTime) and not len(clip[3]): self.parent.seekSlider.addRegion( clip[0].msecsSinceStartOfDay(), clip[1].msecsSinceStartOfDay()) return externalCount
def __init__(self, workspace, documents): super(_UISaveFiles, self).__init__(workspace) self.cancelled = False uic.loadUi(os.path.join(DATA_FILES_PATH, 'ui/SaveFiles.ui'), self) self.buttonBox.clicked.connect(self._onButtonClicked) self._documents = documents for index, document in enumerate(documents): name = document.fileName() if name is None: name = 'untitled' item = QListWidgetItem(name, self.listWidget) if document.filePath() is not None: item.setToolTip(document.filePath()) item.setCheckState(Qt.Checked) # Retitle buttons, add first letter shortcuts for them. bb = self.buttonBox self._shortcut = ( self._firstLetterShortcut(bb.Discard, 'close &Without saving'), self._firstLetterShortcut(bb.Cancel, '&Cancel close'), self._firstLetterShortcut(bb.Save, '&Save checked')) self.buttonBox.button(QDialogButtonBox.Cancel).setFocus()
def first_playlist_dj(self): send = self.sender() id_str = send.objectName() self.lock.acquire() self.listview_lable.setObjectName("internet") if self.src_choose.currentText() == "网易云": if id_str[1] == 'p': self.date.music_name, self.date.music_id = NCOperation.playlist_info( id_str.split('=')[1]) self.listview.clear() # 列表清空 for i in range(len(self.date.music_name)): # 加入选中歌单中的歌曲名 temp = QListWidgetItem(self.date.music_name[i]) temp.setIcon(QIcon("./ico/song.png")) temp.setToolTip("双击播放") self.listview.addItem(temp) elif id_str[1] == 'd': self.player.setMedia( QMediaContent( QUrl(NCOperation.dj_url( id_str.split('=')[1])))) # 设置音频网址 text = self.date.bt_name[self.date.bt_id.index(id_str)] self.disc_title.setText(text) # 显示播放的音频名字 self.disc.setObjectName("") self.listview.setCurrentRow(-1) self.player_setting() elif self.src_choose.currentText() == "QQ音乐": self.message_label.setText("后续跟进") self.lock.release()
def changeGame(self, game): self.game = game self.engine = ResumeEngine(game) self.savedlist.clear() self.matches = [] candidates = self.engine.getCandidates() if not candidates: self.savedlist.hide() self.resumebutton.hide() self.cancelbutton.hide() self.emptyLabel.show() else: self.emptyLabel.hide() for idMatch, candidate in candidates.items(): self.matches.append(idMatch) savedtime = datetime.datetime.strptime( candidate['started'], "%Y-%m-%d %H:%M:%S.%f") strtime = savedtime.strftime("%Y-%m-%d %H:%M:%S") hours, remainder = divmod(int(candidate['elapsed']), 3600) minutes, seconds = divmod(remainder, 60) strelapsed = "{0:02}:{1:02}:{2:02}".format( hours, minutes, seconds) msg = i18n("ResumeBox", 'Saved on {}. Time played: {}').format(strtime, strelapsed) item = QListWidgetItem(msg, self.savedlist) playerlist = "" for player in candidate['players']: playerlist += "\n " + player item.setToolTip(i18n( "ResumeBox", "Players: {}").format(playerlist)) self.savedlist.addItem(item) self.savedlist.show() self.resumebutton.show() self.cancelbutton.show()
def addOnePixmaptoForm(self, item: picInfo): QPixmapCache.clear() if 'pixcount' not in self.__dict__: self.pixcount = 1 else: self.pixcount += 1 logging.getLogger().debug("得到一个图片信息准备加载:{}".format(self.pixcount)) obj = None pItem = None if item.viewPixmap: obj = item.viewPixmap self.viewPicInfos.append(item) pItem = QListWidgetItem( QIcon( obj.scaled(self.icoSize, Qt.KeepAspectRatio, Qt.SmoothTransformation)), '') elif item.viewPixmap_Ico: obj = item.viewPixmap_Ico pItem = QListWidgetItem( QIcon( obj.scaled(self.icoSize, Qt.KeepAspectRatio, Qt.SmoothTransformation)), '') pItem.setSizeHint(self.pdfPageSize) pItem.picInfo = item pItem.setToolTip(item.originalName) pItem.setText(item.icoText if item.icoText else item.originalName) self.ui.listWidget.addItem(pItem) QGuiApplication.processEvents()
def _deleteFiles(self): """Removes files from list and model.""" # Get selected item files = self.selectedItems() # Clear Table self._table.clearTable() # Remove files from list and model for i, file in enumerate(files): idx = self.indexFromItem(file) self.takeItem(idx.row()) self._model.session['datafiles'].pop(idx.row()) # Add dummy if no more data-files left and prepare load if not self._model.dataFilesLoaded(): dummy = QListWidgetItem("No Data Files...") dummy.setToolTip('Click to load files...') dummy.setStatusTip("Click to load files...") self.addItem(dummy) self._status.changeStatus("No Data File(s) Loaded") self._dummy = not self._dummy self._model.prepareForNewLoad() self._rtSpec.updateEntries() self._modelTab.updateWidgets()
def gen_list_item(self, hash_type: str, hash_value: str) -> QListWidgetItem: widget_item = QListWidgetItem() widget_item.setText("%s : %s" % (hash_type, hash_value)) widget_item.setData(Qt.UserRole, hash_value) widget_item.setToolTip("点击复制") return widget_item
def initUI(self): self.setViewMode(QListView.IconMode) for item in self.menus: widgetItem = QListWidgetItem(self) widgetItem.metadata = item widgetItem.setText(item['title']) widgetItem.setToolTip(item.get('description', '')) widgetItem.setIcon(QIcon(item['icon'])) self.addItem(widgetItem) self.setCurrentRow(0) self.setIconSize(QSize(32, 32)) self.setMovement(QListView.Static) self.setUniformItemSizes(True) # self.setSize() self.setStyleSheet("""QListWidget::Item { padding-left: 10px; padding-right: 10px; padding-bottom: 5px; }""") shadow = QGraphicsDropShadowEffect(self) shadow.setColor(Qt.black) shadow.setBlurRadius(10) shadow.setOffset(0, 0) self.setGraphicsEffect(shadow)
def update_account_feed(self): if self.hist_account is None: return updated_feed = self.hist_account.get_account_posts() if len(self.feed) == 0: self.feed = updated_feed else: for post in updated_feed[::-1]: found = False for p in self.feed: if post["authorperm"] == p["authorperm"]: found = True if not found: self.feed.insert(0, post) self.tray.showMessage(post["author"], post["title"]) with self.updateLock: if self.post is None: self.post = self.feed[0] self.triggeredPreview() self.feedListWidget.currentRowChanged.disconnect( self.change_displayed_post) self.feedListWidget.clear() for post in self.feed[::-1]: post_text = "%s - %s" % (post["author"], post["title"]) post_item = QListWidgetItem() post_item.setText(post_text) post_item.setToolTip(post["author"]) self.feedListWidget.insertItem(0, post_item) self.feedListWidget.currentRowChanged.connect( self.change_displayed_post, Qt.QueuedConnection)
def setActions(self, actions): self._actionList.clear() self._actions = [] for funcs, name, filename in actions: item = QListWidgetItem(name) item.setToolTip('\n'.join([func.description() for func in funcs])) item._action = [name, filename] self._actionList.addItem(item)
def load_tests(self): """ Make list of all known tests """ for i in fwtp_core.TestSuiteConfig.KNOWN_TESTS_DESC.keys(): ti = fwtp_core.TestSuiteConfig.KNOWN_TESTS_DESC[i] item = QListWidgetItem(ti.testname, self.listWidget) item.setFlags(item.flags() | Qt.ItemIsUserCheckable) item.setCheckState(Qt.Checked) item.setToolTip(ti.INFO)
def loadImages(self): self.image_list.clear() for root, dir, files in os.walk(os.path.join(self.book.source_path, "images")): for file in files: filename = os.path.join(self.book.source_path, "images", Path(file).name) item = QListWidgetItem() item.setToolTip("Doubleclick image to insert into text") item.setText(Path(file).name) item.setData(1, filename) self.image_list.addItem(item)
def set_prohibited_item(prohibited_item: QtWidgets.QListWidgetItem, item_type: str) -> None: # add list item that user does not have permission to upload prohibited_item.setText(f'{each} ⚠️') prohibited_item.setForeground(QColor(255, 0, 0)) prohibited_item.setToolTip( f'You do not have permission to upload this {item_type}') prohibited_item.setFlags(list_item.flags() & ~QtCore.Qt.ItemIsUserCheckable) prohibited_item.setCheckState(QtCore.Qt.Unchecked)
def refresh(self): self.listWidget.clear() with open('Websites.txt') as fp: lines = fp.read().splitlines() self.websites_list = lines for line in lines: item = QListWidgetItem(line) item.setToolTip('Double clicked to edit') self.listWidget.addItem(item) # self.listWidget.addItems(lines) self.statusbar.showMessage('Refresh successfully', 5000)
def fill_store(self): self.materials.clear() all_files=find_materials() for fl in all_files: b=bibtex() if b.load(os.path.join(get_materials_path(),fl,"mat.bib"))!=False: text=b.get_text(html=False) if text!="": itm = QListWidgetItem(os.path.basename(fl)+" "+text) itm.setIcon(self.mat_icon) itm.setToolTip(text) self.materials.addItem(itm)
def set_restricted_item( restricted_item: QtWidgets.QListWidgetItem) -> None: # add list item (only applies to subdirectories, not files) that user does have full access to restricted_item.setText(f'{each} ⚠️') restricted_item.setForeground(QColor(255, 130, 0)) restricted_item.setToolTip( f'At least some files/folders in this subdirectory cannot be uploaded (you do ' f'not have permission)') restricted_item.setData(QtCore.Qt.UserRole, "subdirectory") restricted_item.setFlags(list_item.flags() | QtCore.Qt.ItemIsUserCheckable) restricted_item.setCheckState(QtCore.Qt.Checked)
def add_view(result): if result == QDialog.Accepted: options = self._dialog.getValues() id_ = generate_id(widget_class.name) self._options[id_] = options item = QListWidgetItem(f"{widget_class.title} ({short_id(id_)})") item.setToolTip(id_) item.setSizeHint(QSize(0, 50)) item.setTextAlignment(Qt.AlignCenter) item.setData(ProcessDataDialog.NameRole, widget_class.name) item.setData(ProcessDataDialog.IdRole, id_) self.lstViews.addItem(item)
def create_my_playlist(self, text, ok): self.lock.acquire() if ok: with open("./my_playlist/" + text + ".json", 'w', encoding='utf-8') as f: json.dump({"playlist": []}, f, ensure_ascii=False) self.date.my_playlist_name.append(text) self.date.my_playlist_text[text] = {"playlist": []} temp = QListWidgetItem(text) temp.setIcon(QIcon("./ico/my_playlist")) temp.setToolTip("双击显示") self.myplaylist_list.addItem(temp) self.lock.release()
def __insertListViewItem(self, name, row = None): ob = self.store._tables[name].ob item = QListWidgetItem(name) doc = str(ob.__doc__) search = re.search(r'\n[ \t]*', doc) if search: doc = re.sub(search.group(), '\n', doc) item.setToolTip(str(doc)) if row is None: self.listView.addItem(item) else: self.listView.insertItem(row, item)
def _list_fill(self): if not os.path.isfile(CONF_INSTALL): return with open(CONF_INSTALL, encoding='utf-8') as file: self.archives = json.loads(file.read()) self.w_list.clear() for arch in self.archives: item = QListWidgetItem(self.w_list) item.setIcon(QIcon(ZIP)) item.setText(os.path.basename(arch)) item.setToolTip(arch) self.w_list.addItem(item)
def add_item(self, pixmap, file): icon = QIcon( pixmap.scaled(QSize(100, 50), Qt.KeepAspectRatio, transformMode=1)) if isinstance(file, Folder): item = QListWidgetItem(file.get_name(), self.listWidget) else: item = QListWidgetItem(os.path.basename(file), self.listWidget) item.setToolTip(file) item.setStatusTip(file) item.setIcon(icon)
def refresh_pep8_list(self, pep8): self._outRefresh = False self.listPep8.clear() for lineno in pep8: linenostr = 'L%s\t' % str(lineno + 1) for data in pep8[lineno]: item = QListWidgetItem(linenostr + data.split('\n')[0]) item.setToolTip(linenostr + data.split('\n')[0]) item.setData(Qt.UserRole, lineno) self.listPep8.addItem(item) self.pep8Label.setText(self.tr("PEP8 Errors: %s") % len(pep8)) self._outRefresh = True
def refresh_error_list(self, errors): self._outRefresh = False self.listErrors.clear() for lineno in errors: linenostr = 'L%s\t' % str(lineno + 1) for data in errors[lineno]: item = QListWidgetItem(linenostr + data) item.setToolTip(linenostr + data) item.setData(Qt.UserRole, lineno) self.listErrors.addItem(item) self.errorsLabel.setText(self.tr("Static Errors: %s") % len(errors)) self._outRefresh = True
def set_content(self): for t, table in enumerate(self.allocation): drag_list = self.drag_lists[t] label = self.labels[t] order_cluster_dict = self.ctx.app_data_manager.get_fields_cluster_dict( ) order_diverse_dict = self.ctx.app_data_manager.get_fields_diverse_dict( ) cats = {**order_cluster_dict, **order_diverse_dict} # set drag_list items drag_list.clear() r = 0 for pid in table: newItem = QListWidgetItem() newItem.setData(Qt.UserRole, pid) print_label = self.ctx.app_data_manager.get_print_labels(pid) newItem.setText(print_label) tooltip_infos = [print_label] for field_key in cats: field_key_label = self.ctx.app_data.peopledata_keys[ field_key] field_pid_val = self.ctx.app_data_manager.load_details( pid, field_key) tooltip_infos.append("{}: {}".format( field_key_label, field_pid_val)) newItem.setToolTip("\n".join(tooltip_infos)) drag_list.insertItem(r, newItem) r += 1 label_strings = [ "<p><strong>Total: {}</strong></p>".format(len(table)) ] for cat_key, cat_val_terms in cats.items(): label_strings.append("<p>{}:<br/>".format( self.ctx.app_data.peopledata_keys[cat_key])) label_strings_cat = [] for cat_val_term in cat_val_terms: occurences = self.ctx.app_data_manager.get_occurences( self.a, t, cat_key, cat_val_term) label_strings_cat.append("{} {}".format( occurences, cat_val_term)) label_strings.append("<br/>".join(label_strings_cat)) label_strings.append("</p>") label_string = " ".join(label_strings) label.setText(label_string) self.wgtMain.resize(self.hboxMain.sizeHint().width(), self.wgtSubs[0].sizeHint().height() + 30)
def _initList(self): """Initializes and configures the table.""" self.setContextMenuPolicy(Qt.CustomContextMenu) self.customContextMenuRequested.connect(self._onContext) self.setAcceptDrops(True) self.setDragEnabled(True) self.setSelectionMode(QAbstractItemView.ExtendedSelection) dummy = QListWidgetItem("No Data Files...") dummy.setToolTip('Click to load files...') dummy.setStatusTip("Click to load files...") self.addItem(dummy) self.clicked.connect(self._onClick)
def fill_store(self): self.materials.clear() print(get_materials_path()) all_files = find_materials() for fl in all_files: text = get_ref_text(os.path.join(get_materials_path(), fl, "n.omat"), html=False) if text != None: itm = QListWidgetItem(os.path.basename(fl) + " " + text) itm.setIcon(self.mat_icon) itm.setToolTip(text) self.materials.addItem(itm)
def load_saved_playlist(self): """Load the saved playlist if user setting permits.""" saved_playlist = "{}/.m3u" .format(self.playlist_location) if os.path.exists(saved_playlist): playlist = QUrl().fromLocalFile(saved_playlist) self.playlist.load(playlist) self.player.setPlaylist(self.playlist) for song_index in range(self.playlist.mediaCount()): file_info = self.playlist.media(song_index).canonicalUrl().fileName() playlist_item = QListWidgetItem(file_info) playlist_item.setToolTip(file_info) self.playlist_view.addItem(playlist_item) self.playlist_view.setCurrentRow(0)
def open_file(self): """Open the selected file and add it to a new playlist.""" filename, success = QFileDialog.getOpenFileName(self, 'Open File', '', 'Audio (*.mp3 *.flac)', '', QFileDialog.ReadOnly) if success: file_info = QFileInfo(filename).fileName() playlist_item = QListWidgetItem(file_info) self.playlist.clear() self.playlist_view.clear() self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(filename))) self.player.setPlaylist(self.playlist) playlist_item.setToolTip(file_info) self.playlist_view.addItem(playlist_item) self.playlist_view.setCurrentRow(0) self.player.play()
def open_multiple_files(self): """Open the selected files and add them to a new playlist.""" filenames, success = QFileDialog.getOpenFileNames(self, 'Open Multiple Files', '', 'Audio (*.mp3 *.flac)', '', QFileDialog.ReadOnly) if success: self.playlist.clear() self.playlist_view.clear() for file in natsort.natsorted(filenames, alg=natsort.ns.PATH): file_info = QFileInfo(file).fileName() playlist_item = QListWidgetItem(file_info) self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(file))) self.player.setPlaylist(self.playlist) playlist_item.setToolTip(file_info) self.playlist_view.addItem(playlist_item) self.playlist_view.setCurrentRow(0) self.player.play()
def updateSheets(self): if self.sheets is not None and self.ownsheet is not None: self.listSheetItems = {} self.listWidget.clear() for sheetId in self.sheets: if not sheetId == self.ownsheet: newItem = QListWidgetItem(self.sheets[sheetId]) newItem.setToolTip(str(sheetId)) newItem.setData(Qt.UserRole, sheetId) self.listSheetItems[sheetId] = newItem self.listWidget.addItem(newItem) if sheetId == self.selectedSheet: boldFont = QFont() boldFont.setBold(True) newItem.setFont(boldFont)
def __init__(self, unsaved_files, parent=None): super().__init__(parent) self._ninja = parent self.setWindowTitle(translations.TR_IDE_CONFIRM_EXIT_TITLE) vbox = QVBoxLayout(self) self._unsave_files_list = QListWidget() self._unsave_files_list.setSelectionMode(QListWidget.ExtendedSelection) vbox.addWidget(QLabel(translations.TR_IDE_CONFIRM_EXIT_BODY)) vbox.addWidget(self._unsave_files_list) button_box = QDialogButtonBox(self) standard_icon = self.style().standardIcon btn = button_box.addButton( translations.TR_CANCEL, QDialogButtonBox.RejectRole) btn.setIcon(standard_icon(self.style().SP_DialogCloseButton)) self._btn_save_selected = button_box.addButton( translations.TR_SAVE_SELECTED, QDialogButtonBox.AcceptRole) self._btn_save_selected.setIcon( standard_icon(self.style().SP_DialogSaveButton)) btn_save_all = button_box.addButton( translations.TR_SAVE_ALL, QDialogButtonBox.AcceptRole) btn_save_all.setIcon(standard_icon(self.style().SP_DialogApplyButton)) btn_donot_save = button_box.addButton( translations.TR_DONOT_SAVE, QDialogButtonBox.DestructiveRole) btn_donot_save.setIcon(standard_icon(self.style().SP_DialogNoButton)) vbox.addWidget(button_box) for nfile in unsaved_files: item = QListWidgetItem(nfile.display_name) item.setData(Qt.UserRole, nfile) item.setToolTip(nfile.file_path) self._unsave_files_list.addItem(item) # Connections button_box.rejected.connect(self.reject) button_box.accepted.connect(self._save_selected) btn_donot_save.clicked.connect(self._discard) btn_save_all.clicked.connect(self._save_all) self._unsave_files_list.itemSelectionChanged.connect( self._on_selection_changed) self._unsave_files_list.selectAll()
def populatesThemesList(self): paths = allPaths("resources/themes") current = settings.fullScreenTheme self.lstThemes.clear() for p in paths: lst = [i for i in os.listdir(p) if os.path.splitext(i)[1] == ".theme"] for t in lst: theme = os.path.join(p, t) editable = not appPath() in theme n = getThemeName(theme) item = QListWidgetItem(n) item.setData(Qt.UserRole, theme) item.setData(Qt.UserRole + 1, editable) item.setToolTip("{}{}".format( n, self.tr(" (read-only)") if not editable else "")) thumb = os.path.join(p, t.replace(".theme", ".jpg")) px = QPixmap(200, 120) px.fill(Qt.white) if not os.path.exists(thumb): currentScreen = qApp.desktop().screenNumber(self) screenRect = qApp.desktop().screenGeometry(currentScreen) thumb = createThemePreview(theme, screenRect) icon = QPixmap(thumb).scaled(200, 120, Qt.KeepAspectRatio) painter = QPainter(px) painter.drawPixmap(px.rect().center() - icon.rect().center(), icon) painter.end() item.setIcon(QIcon(px)) self.lstThemes.addItem(item) if current and current in t: self.lstThemes.setCurrentItem(item) current = None self.lstThemes.setIconSize(QSize(200, 120)) if current: # the theme from settings wasn't found # select the last from the list self.lstThemes.setCurrentRow(self.lstThemes.count() - 1)
def refresh_lists(self, migration): """Refresh the list of code suggestions.""" self._migration, base_lineno = migration, -1 self.current_list.clear() for lineno in sorted(migration.keys()): linenostr = 'L{line_number}\n'.format(line_number=str(lineno + 1)) data = migration[lineno] lines = data[0].split('\n') if base_lineno == data[1]: continue base_lineno = data[1] message = '' for line in lines: if line.startswith('-'): message += '{line_to_load}\n'.format(line_to_load=line) item = QListWidgetItem(linenostr + message) item.setToolTip(linenostr + message) item.setData(Qt.UserRole, lineno) self.current_list.addItem(item)
def refresh_lists(self, migration): self._migration = migration self.current_list.clear() base_lineno = -1 for lineno in sorted(migration.migration_data.keys()): linenostr = 'L%s\n' % str(lineno + 1) data = migration.migration_data[lineno] lines = data[0].split('\n') if base_lineno == data[1]: continue base_lineno = data[1] message = '' for line in lines: if line.startswith('-'): message += '%s\n' % line item = QListWidgetItem(linenostr + message) item.setToolTip(linenostr + message) item.setData(Qt.UserRole, lineno) self.current_list.addItem(item)
def open_playlist(self): """Load an M3U or PLS file into a new playlist.""" playlist, success = QFileDialog.getOpenFileName(self, 'Open Playlist', '', 'Playlist (*.m3u *.pls)', '', QFileDialog.ReadOnly) if success: playlist = QUrl.fromLocalFile(playlist) self.playlist.clear() self.playlist_view.clear() self.playlist.load(playlist) self.player.setPlaylist(self.playlist) for song_index in range(self.playlist.mediaCount()): file_info = self.playlist.media(song_index).canonicalUrl().fileName() playlist_item = QListWidgetItem(file_info) playlist_item.setToolTip(file_info) self.playlist_view.addItem(playlist_item) self.playlist_view.setCurrentRow(0) self.player.play()
def open_directory(self): """Open the selected directory and add the files within to an empty playlist.""" directory = QFileDialog.getExistingDirectory(self, 'Open Directory', '', QFileDialog.ReadOnly) if directory: self.playlist.clear() self.playlist_view.clear() for dirpath, __, files in os.walk(directory): for filename in natsort.natsorted(files, alg=natsort.ns.PATH): file = os.path.join(dirpath, filename) if filename.endswith(('mp3', 'flac')): self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(file))) playlist_item = QListWidgetItem(filename) playlist_item.setToolTip(filename) self.playlist_view.addItem(playlist_item) self.player.setPlaylist(self.playlist) self.playlist_view.setCurrentRow(0) self.player.play()
def createGroupItem(self, name, content = None): if not content: group = self.iface.getGroup(name) localName, icon_path = unicode(group.localName), group.icon package_count = len(self.state.groupPackages(name)) if package_count <= 0: return else: localName, icon_path = content[0], content[1] package_count = content[2] icon = KIcon(icon_path, KIconLoader.SizeSmallMedium) if icon.isNull(): icon = self.defaultIcon text = "%s (%d)" % (localName, package_count) item = QListWidgetItem(icon, text, self) item.setToolTip(localName) item.setData(Qt.UserRole, QVariant(unicode(name))) item.setSizeHint(QSize(0, KIconLoader.SizeMedium)) self._list[name] = item
def open_media_library(self, index): """Open a directory or file from the media library into an empty playlist.""" self.playlist.clear() self.playlist_view.clear() if self.library_model.fileName(index).endswith(('mp3', 'flac')): self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(self.library_model.filePath(index)))) self.playlist_view.addItem(self.library_model.fileName(index)) elif self.library_model.isDir(index): directory = self.library_model.filePath(index) for dirpath, __, files in os.walk(directory): for filename in natsort.natsorted(files, alg=natsort.ns.PATH): file = os.path.join(dirpath, filename) if filename.endswith(('mp3', 'flac')): self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(file))) playlist_item = QListWidgetItem(filename) playlist_item.setToolTip(filename) self.playlist_view.addItem(playlist_item) self.player.setPlaylist(self.playlist) self.player.play()
def _addView(self, win, fn=None, noName="", next=False): """ Protected method to add a view (i.e. window). @param win editor assembly to be added @param fn filename of this editor (string) @param noName name to be used for an unnamed editor (string) @param next flag indicating to add the view next to the current view (bool) """ editor = win.getEditor() if fn is None: if not noName: self.untitledCount += 1 noName = self.tr("Untitled {0}").format(self.untitledCount) self.viewlist.addItem(noName) editor.setNoName(noName) else: txt = os.path.basename(fn) if not QFileInfo(fn).isWritable(): txt = self.tr("{0} (ro)").format(txt) itm = QListWidgetItem(txt) itm.setToolTip(fn) self.viewlist.addItem(itm) self.currentStack.addWidget(win) self.currentStack.setCurrentWidget(win) editor.captionChanged.connect(self.__captionChange) editor.cursorLineChanged.connect(self.__cursorLineChanged) index = self.editors.index(editor) self.viewlist.setCurrentRow(index) editor.setFocus() if fn: self.changeCaption.emit(fn) self.editorChanged.emit(fn) self.editorLineChanged.emit(fn, editor.getCursorPosition()[0] + 1) else: self.changeCaption.emit("") self.editorChangedEd.emit(editor)
def refresh_lists(self, errors, pep8): self._outRefresh = False self.listErrors.clear() self.listPep8.clear() for lineno in errors.errorsSummary: linenostr = 'L%s\t' % str(lineno + 1) for data in errors.errorsSummary[lineno]: item = QListWidgetItem(linenostr + data) item.setToolTip(linenostr + data) item.setData(Qt.UserRole, lineno) self.listErrors.addItem(item) self.errorsLabel.setText(_translate("ErrorsWidget", "Static Errors: %s") % len(errors.errorsSummary)) for lineno in pep8.pep8checks: linenostr = 'L%s\t' % str(lineno + 1) for data in pep8.pep8checks[lineno]: item = QListWidgetItem(linenostr + data.split('\n')[0]) item.setToolTip(linenostr + data.split('\n')[0]) item.setData(Qt.UserRole, lineno) self.listPep8.addItem(item) self.pep8Label.setText(_translate("ErrorsWidget", "PEP8 Errors: %s") % len(pep8.pep8checks)) self._outRefresh = True
def makePopupMenu(self): index = self.currentIndex() sel = self.getSelection() clipboard = qApp.clipboard() menu = QMenu(self) # Get index under cursor pos = self.viewport().mapFromGlobal(QCursor.pos()) mouseIndex = self.indexAt(pos) # Get index's title if mouseIndex.isValid(): title = mouseIndex.internalPointer().title() elif self.rootIndex().parent().isValid(): # mouseIndex is the background of an item, so we check the parent mouseIndex = self.rootIndex().parent() title = mouseIndex.internalPointer().title() else: title = qApp.translate("outlineBasics", "Root") if len(title) > 25: title = title[:25] + "…" # Open Item action self.actOpen = QAction(QIcon.fromTheme("go-right"), qApp.translate("outlineBasics", "Open {}".format(title)), menu) self.actOpen.triggered.connect(self.openItem) menu.addAction(self.actOpen) # Open item(s) in new tab if mouseIndex in sel and len(sel) > 1: actionTitle = qApp.translate("outlineBasics", "Open {} items in new tabs").format(len(sel)) self._indexesToOpen = sel else: actionTitle = qApp.translate("outlineBasics", "Open {} in a new tab").format(title) self._indexesToOpen = [mouseIndex] self.actNewTab = QAction(QIcon.fromTheme("go-right"), actionTitle, menu) self.actNewTab.triggered.connect(self.openItemsInNewTabs) menu.addAction(self.actNewTab) menu.addSeparator() # Add text / folder self.actAddFolder = QAction(QIcon.fromTheme("folder-new"), qApp.translate("outlineBasics", "New &Folder"), menu) self.actAddFolder.triggered.connect(self.addFolder) menu.addAction(self.actAddFolder) self.actAddText = QAction(QIcon.fromTheme("document-new"), qApp.translate("outlineBasics", "New &Text"), menu) self.actAddText.triggered.connect(self.addText) menu.addAction(self.actAddText) menu.addSeparator() # Copy, cut, paste, duplicate self.actCut = QAction(QIcon.fromTheme("edit-cut"), qApp.translate("outlineBasics", "C&ut"), menu) self.actCut.triggered.connect(self.cut) menu.addAction(self.actCut) self.actCopy = QAction(QIcon.fromTheme("edit-copy"), qApp.translate("outlineBasics", "&Copy"), menu) self.actCopy.triggered.connect(self.copy) menu.addAction(self.actCopy) self.actPaste = QAction(QIcon.fromTheme("edit-paste"), qApp.translate("outlineBasics", "&Paste"), menu) self.actPaste.triggered.connect(self.paste) menu.addAction(self.actPaste) # Rename / duplicate / remove items self.actDelete = QAction(QIcon.fromTheme("edit-delete"), qApp.translate("outlineBasics", "&Delete"), menu) self.actDelete.triggered.connect(self.delete) menu.addAction(self.actDelete) self.actRename = QAction(QIcon.fromTheme("edit-rename"), qApp.translate("outlineBasics", "&Rename"), menu) self.actRename.triggered.connect(self.rename) menu.addAction(self.actRename) menu.addSeparator() # POV self.menuPOV = QMenu(qApp.translate("outlineBasics", "Set POV"), menu) mw = mainWindow() a = QAction(QIcon.fromTheme("dialog-no"), qApp.translate("outlineBasics", "None"), self.menuPOV) a.triggered.connect(lambda: self.setPOV("")) self.menuPOV.addAction(a) self.menuPOV.addSeparator() menus = [] for i in [qApp.translate("outlineBasics", "Main"), qApp.translate("outlineBasics", "Secondary"), qApp.translate("outlineBasics", "Minor")]: m = QMenu(i, self.menuPOV) menus.append(m) self.menuPOV.addMenu(m) mpr = QSignalMapper(self.menuPOV) for i in range(mw.mdlCharacter.rowCount()): a = QAction(mw.mdlCharacter.icon(i), mw.mdlCharacter.name(i), self.menuPOV) a.triggered.connect(mpr.map) mpr.setMapping(a, int(mw.mdlCharacter.ID(i))) imp = toInt(mw.mdlCharacter.importance(i)) menus[2 - imp].addAction(a) mpr.mapped.connect(self.setPOV) menu.addMenu(self.menuPOV) # Status self.menuStatus = QMenu(qApp.translate("outlineBasics", "Set Status"), menu) # a = QAction(QIcon.fromTheme("dialog-no"), qApp.translate("outlineBasics", "None"), self.menuStatus) # a.triggered.connect(lambda: self.setStatus("")) # self.menuStatus.addAction(a) # self.menuStatus.addSeparator() mpr = QSignalMapper(self.menuStatus) for i in range(mw.mdlStatus.rowCount()): a = QAction(mw.mdlStatus.item(i, 0).text(), self.menuStatus) a.triggered.connect(mpr.map) mpr.setMapping(a, i) self.menuStatus.addAction(a) mpr.mapped.connect(self.setStatus) menu.addMenu(self.menuStatus) # Labels self.menuLabel = QMenu(qApp.translate("outlineBasics", "Set Label"), menu) mpr = QSignalMapper(self.menuLabel) for i in range(mw.mdlLabels.rowCount()): a = QAction(mw.mdlLabels.item(i, 0).icon(), mw.mdlLabels.item(i, 0).text(), self.menuLabel) a.triggered.connect(mpr.map) mpr.setMapping(a, i) self.menuLabel.addAction(a) mpr.mapped.connect(self.setLabel) menu.addMenu(self.menuLabel) menu.addSeparator() # Custom icons if self.menuCustomIcons: menu.addMenu(self.menuCustomIcons) else: self.menuCustomIcons = QMenu(qApp.translate("outlineBasics", "Set Custom Icon"), menu) a = QAction(qApp.translate("outlineBasics", "Restore to default"), self.menuCustomIcons) a.triggered.connect(lambda: self.setCustomIcon("")) self.menuCustomIcons.addAction(a) self.menuCustomIcons.addSeparator() txt = QLineEdit() txt.textChanged.connect(self.filterLstIcons) txt.setPlaceholderText("Filter icons") txt.setStyleSheet("QLineEdit { background: transparent; border: none; }") act = QWidgetAction(self.menuCustomIcons) act.setDefaultWidget(txt) self.menuCustomIcons.addAction(act) self.lstIcons = QListWidget() for i in customIcons(): item = QListWidgetItem() item.setIcon(QIcon.fromTheme(i)) item.setData(Qt.UserRole, i) item.setToolTip(i) self.lstIcons.addItem(item) self.lstIcons.itemClicked.connect(self.setCustomIconFromItem) self.lstIcons.setViewMode(self.lstIcons.IconMode) self.lstIcons.setUniformItemSizes(True) self.lstIcons.setResizeMode(self.lstIcons.Adjust) self.lstIcons.setMovement(self.lstIcons.Static) self.lstIcons.setStyleSheet("background: transparent; background: none;") self.filterLstIcons("") act = QWidgetAction(self.menuCustomIcons) act.setDefaultWidget(self.lstIcons) self.menuCustomIcons.addAction(act) menu.addMenu(self.menuCustomIcons) # Disabling stuff if not clipboard.mimeData().hasFormat("application/xml"): self.actPaste.setEnabled(False) if len(sel) == 0: self.actCopy.setEnabled(False) self.actCut.setEnabled(False) self.actRename.setEnabled(False) self.actDelete.setEnabled(False) self.menuPOV.setEnabled(False) self.menuStatus.setEnabled(False) self.menuLabel.setEnabled(False) self.menuCustomIcons.setEnabled(False) if len(sel) > 1: self.actRename.setEnabled(False) return menu