class StringFilterWidget(AbstractFilterWidget): def __init__(self, field: str, parent=None): super().__init__(parent) self.field = field vlayout = QVBoxLayout() vlayout.setContentsMargins(0, 0, 0, 0) self.edit = QLineEdit() vlayout.addWidget(self.edit) self.setLayout(vlayout) self.completer = QCompleter() self.completer_model = QStringListModel() self.completer.setModel(self.completer_model) self.edit.setCompleter(self.completer) self.edit.textChanged.connect(self.changed) def setup(self, conn: sqlite3.Connection): self.completer_model.setStringList( sql.get_field_unique_values(conn, self.field)) def get_filters(self): name = self.field value = self.edit.text() if not value: return "" else: return {"field": name, "operator": "~", "value": value}
class CustomLineEdit(QLineEdit): mousePressed = QtCore.Property(QMouseEvent) tagSelected = QtCore.Signal(str) def __init__(self, parent): super(self.__class__, self).__init__() self.model = QStringListModel() self.setCompleter(QCompleter()) self.completer().setModel(self.model) self.completer().setCompletionMode(QCompleter.PopupCompletion) self.completer().activated.connect(self.selected) self.textEdited.connect(self.slot_text_edited) self.parent = parent self.setPlaceholderText("Type tags here") def slot_text_edited(self, text): self.completer().setCompletionMode( QCompleter.UnfilteredPopupCompletion if text == '' else QCompleter.PopupCompletion) def selected(self, txt): self.tagSelected.emit(txt) def set_list(self, qsl): self.model.setStringList(qsl) def mousePressEvent(self, e): self.completer().complete() def focusInEvent(self, e): self.completer().complete() def focusOutEvent(self, e): pass
def open_config(): from .designer_wrapper import ConfigInvoker, QmlWrapper from PySide2.QtCore import QStringListModel paths = shared.config["default_input"] model = QStringListModel() model.setStringList(paths) configinvoker = ConfigInvoker(model) QmlWrapper.from_resource("Config", properties={"HP": configinvoker, "Paths": model})
class StationList(QListView): def __init__(self, items: list): super().__init__() self.stringListModel = QStringListModel() self.stringListModel.setStringList(items) self.setModel(self.stringListModel) self.setStyleSheet("font-size: 23px;") self.setSpacing(0) self.setEditTriggers(QAbstractItemView.NoEditTriggers)
def initialization(self): li = ["eat", "drink"] for l in li: item = self.get_item(l) listModel = QStringListModel() listModel.setStringList(item) model_1 = getattr(self, "list_{}".format(l)) model_2 = getattr(self, "list_{}_arr".format(l)) model_2.clear() model_2 += item model_1.setModel(listModel)
def open_user_config(datacontainer): from .designer_wrapper import UserConfigInvoker, QmlWrapper from PySide2.QtCore import QStringListModel userlist = sorted(shared.userconfig["users"].keys()) model = QStringListModel() model.setStringList(userlist) userconfiginvoker = UserConfigInvoker(model, userlist, datacontainer["doctors"]) QmlWrapper.from_resource("UserConfig", properties={"Users": model, "HP": userconfiginvoker, "Doctors": userconfiginvoker.doctorlist})
def columns_to_view(self, columns, view, chosen_row=None): """把一个路径下的文件在view中显示出来 Arguments: path {str} -- 科目、地区、试卷的路径 view {object} -- 用来显示的UI组件 """ # 读取数据库所有row的某column # 1. column -> 模型 # 2. 模型 -> view # 如果需要选中row,则选中它 model = QStringListModel() model.setStringList(columns) view.setModel(model) if chosen_row is not None: view.setCurrentIndex(chosen_row)
def available_db_combo(self): db_files = [] db_list_model = QStringListModel() for subdir, dirs, files in os.walk(os.path.dirname(os.path.realpath(__file__))): for file in files: filepath = subdir + os.path.sep + file if filepath.endswith(".db"): if filepath not in db_files: db_files.append(file[:-3]) db_list_model.setStringList(db_files) return db_list_model.stringList()
def initUI(self): self.setWindowTitle("list view") self.setGeometry(500,500,300,300) listview = QListView() slm = QStringListModel() self.qList = ['item1','item2','item3','item4'] slm.setStringList(self.qList) listview.setModel(slm) listview.clicked.connect(self.clicked) layout = QVBoxLayout() layout.addWidget(listview) self.setLayout(layout) self.show()
class Window(QMainWindow): def __init__(self): super().__init__() # load the ui file self.ui = QUiLoader().load('listview_manip.ui') # connect signals/slots self.ui.load_btn.clicked.connect(self.on_load_btn_click) # you can access form objects directly ... # self.ui.<name_of_object>.<some_method>() # or search for them ... # self.found_object = self.ui.findChild(QPlainTextEdit, 'plainTextEdit') # or setup shorter references #self.my_text = self.ui.plainTextEdit # Test data in a model self.users = ['User 1', 'User 2', 'User 3'] self.lv_model = QStringListModel() self.lv_model.setStringList(self.users) # # Attach the model and selection events self.ui.file_view.setModel(self.lv_model) self.ui.file_view.selectionModel().selectionChanged.connect( self.item_selected) def item_selected(self): index = self.ui.file_view.currentIndex( ) # returns the primary QModelIndex self.ui.test_lbl.setText(index.data()) def on_load_btn_click(self): print('click!') file_name = self.load_file() self.ui.test_lbl.setText(file_name) def load_file(self): file_name = QFileDialog.getOpenFileName(self) #tr('Open AHLTA template'), '', tr('AHLTA template (*.txt)')) return file_name
class ChoiceFilterWidget(AbstractFilterWidget): def __init__(self, field: str, parent=None): super().__init__(parent) self.field = field vlayout = QVBoxLayout() vlayout.setContentsMargins(0, 0, 0, 0) self.view = QListView() self.model = QStringListModel() self.view.setModel(self.model) vlayout.addWidget(self.view) self.setLayout(vlayout) def setup(self, conn: sqlite3.Connection): self.model.setStringList(sql.get_field_unique_values(conn, self.field)) def get_filters(self): name = self.field return ""
class rename_one(QWidget): def __init__(self,parent=None): super().__init__(parent) self.mydelegate = MyDelegate() self.listview = QListView() self.mymodel = QStringListModel() self.listview.setModel(self.mymodel) # 设置我们自己的delegate self.listview.setItemDelegate(self.mydelegate) self.battle_allies=r'battle_allies' self.battle_allies_list=[] for i in range (1,11): self.battle_allies_list.append(self.battle_allies+'%s.xml'%str(i)) self.mymodel.setStringList(self.battle_allies_list) print(self.battle_allies_list) print(self.mymodel.index(2,0).data())
class NewsHandler(QObject): def __init__(self, context, parent=None): super(NewsHandler, self).__init__(parent) self.win = parent self.ctx = context @Slot(result=str) def getNews(self): self.headlinesurl = "https://news.google.com/?hl=fr&gl=FR&ceid=FR:fr&output=rss" self.feed = feedparser.parse(self.headlinesurl) self.newslist = [post.title for post in self.feed.entries[1:6]] return "\n".join(self.newslist) @Slot() def getListNews(self): self.headlinesurl = "https://news.google.com/?hl=fr&gl=FR&ceid=FR:fr&output=rss" self.feed = feedparser.parse(self.headlinesurl) self.newslist = [post.title for post in self.feed.entries[1:6]] self.newsmodel = QStringListModel() self.newsmodel.setStringList(self.newslist) self.ctx.setContextProperty("newsmodel", self.newsmodel)
def using_model(): app = QApplication() numbers = ['One', 'Two', 'Three', 'Four', 'Five'] model = QStringListModel() model.setStringList(numbers) list = QListView() list.setModel(model) firstTableView = QTableView() secondTableView = QTableView() firstTableView.setModel(model) secondTableView.setModel(model) secondTableView.setSelectionModel(firstTableView.selectionModel()) list.show() firstTableView.show() secondTableView.show() app.exec_()
def _create_completer(self): """Create Completer with his model Fill the model with the SQL keywords and database fields """ model = QStringListModel() completer = QCompleter() keywords = [] samples = [i["name"] for i in sql.get_samples(self.conn)] selections = [i["name"] for i in sql.get_selections(self.conn)] for field in sql.get_fields(self.conn): if field["category"] == "samples": for sample in samples: keywords.append("sample['{}'].{}".format(sample, field["name"])) else: keywords.append(field["name"]) keywords.extend(VqlSyntaxHighlighter.sql_keywords) keywords.extend(selections) model.setStringList(keywords) completer.setModel(model) return completer
def __init__(self, parent, items): super(QTagWidget, self).__init__() self.parent = parent self.items = items self.tags = [] self.mainFrame = QFrame() self.mainFrame.setStyleSheet( 'border:1px solid #76797C; border-radius: 1px;') self.mainLayout = QVBoxLayout() self.mainLayout.setContentsMargins(0, 0, 0, 0) self.setLayout(self.mainLayout) self.mainLayout.addWidget(self.mainFrame) self.hLayout = QHBoxLayout() self.hLayout.setSpacing(4) self.lineEdit = QLineEdit() self.lineEdit.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum) completer = QPartialMatchCompleter(self.lineEdit) completer.setCompletionMode(QCompleter.PopupCompletion) self.lineEdit.setCompleter(completer) model = QStringListModel() completer.setModel(model) model.setStringList(self.items) self.mainFrame.setLayout(self.hLayout) self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) self.hLayout.setContentsMargins(2, 2, 2, 2) self.refresh() self.setup_ui()
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() #ui self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.comboBox_dict.addItems(dicts) #signal self.ui.pushButton_create.clicked.connect(self.createBoard) self.ui.pushButton_save.clicked.connect(self.saveBoard) self.ui.pushButton_open.clicked.connect(self.OpenImages) self.ui.tableView.clicked.connect(self.showImg) #列表图片显示 self.ui.pushButton_calib.clicked.connect(self.calib) self.ui.pushButton_saveParameter.clicked.connect(self.saveParameter) self.ui.pushButton_output.clicked.connect(self.saveCameraGroup) self.ui.pushButton_clear.clicked.connect(self.clearGroup) self.ui.listView_Camera.clicked.connect(self.showCamera) #property self.model = QStandardItemModel() #tab 1 self.cameraListModel = QStringListModel() #tab 2 self.cameraLists = [] self.ui.listView_Camera.setModel(self.cameraListModel) self.caliber = None self.cameraGroup = CameraGroup.CameraGroup() #other self.calibBoard = CharucoBoard.ChessBoard() self.board = None self.boardType = 0 @Slot() #CreateBoard def createBoard(self): dict = self.ui.comboBox_dict.currentIndex() numX = int(self.ui.lineEdit_numX.text()) numY = int(self.ui.lineEdit_numY.text()) squareSize = float(self.ui.lineEdit_squareSize.text()) dpi = int(self.ui.lineEdit_DPI.text()) imgSize = (float(self.ui.lineEdit_printX.text()), float(self.ui.lineEdit_printY.text())) if dict == 0: self.boardType = 0 self.calibBoard = ChessBoard.ChessBoard() self.board = self.calibBoard.create((numX, numY), squareSize, dpi, imgSize) # Create Board else: self.boardType = 1 self.calibBoard = CharucoBoard.CharucoBoard() self.board = self.calibBoard.create(numX, numY, dict - 1, squareSize, imgSize, dpi) #Create Board if self.board is None: ## splite Qt segment self.ui.label.setText("Create Failed,Please confire parameter!") return # showBoard image = QImage(self.board[:], self.board.shape[1], self.board.shape[0], self.board.shape[1], QImage.Format_Grayscale8) #ndarray -> QImage showBoard = QPixmap(image) #QImage -> Qpixmap if showBoard.width() > showBoard.height(): #resize Qpixmap showBoard = showBoard.scaledToWidth(self.ui.label.width()) else: showBoard = showBoard.scaledToHeight(self.ui.label.height()) self.ui.label.setPixmap(showBoard) #show @Slot() #SaveBoard def saveBoard(self): name = QFileDialog.getSaveFileName(self, 'Save Board', '../', "Image(*.jpg *.png)") cv.imwrite(name[0], self.board) self.calibBoard.saveConfig(os.path.dirname(name[0])) @Slot() #cereat Images data model def OpenImages(self): self.cacheDir = '' fileList = QFileDialog.getOpenFileNames(self, "Load Files", '../') self.model = QStandardItemModel() for name in fileList[0]: item = QStandardItem(os.path.basename(name)) #QIcon(name), item.setData(name) item2 = QStandardItem('NULL') self.model.appendRow([item, item2]) self.ui.tableView.setModel(self.model) @Slot() def showImg(self, index): if self.cacheDir == '': return currentImg = QPixmap(self.cacheDir + '/marked_' + self.model.item(index.row(), 0).text()) if currentImg.width() > currentImg.height(): currentImg = currentImg.scaledToWidth(self.ui.label_show.width()) else: currentImg = currentImg.scaledToHeight(self.ui.label_show.height()) self.ui.label_show.setPixmap(currentImg) @Slot() def calib(self): #Calib n = self.model.rowCount() if n == 0: return # strictDetection=2 if self.ui.checkBox_strick.isChecked() else 1 calibType = self.ui.comboBox_detectType.currentIndex() isFisheLen = self.ui.checkBox_isFish.isChecked() self.caliber = Calib.Calib(calibType, isFisheLen, self.calibBoard) path = self.model.item(0, 0).data() #directionary related self.cacheDir = os.path.dirname(path) + '/DetectCache' if not os.path.exists(self.cacheDir): os.mkdir(self.cacheDir) validIndex = [] for i in range(n): #detect print(path) path = self.model.item(i, 0).data() img = cv.imread(path) markedImg = self.caliber.detectCorners(img) if markedImg is None: markedImg = img else: validIndex.append(i) cv.imwrite( self.cacheDir + '/marked_' + self.model.item(i, 0).text(), markedImg) rerro = self.caliber.calibCamera(img.shape[1::-1]) #calib self.ui.statusbar.showMessage("重投影误差(平方根):" + str(rerro)) for i in range(len(validIndex)): #each image reproject erro erro = self.caliber.calcProjectErro(i) self.model.item(validIndex[i], 1).setText(str(erro)) @Slot() def saveParameter(self): if self.caliber is None: return self.cameraGroup.cameras.append(self.caliber.getCameraParameter()) id = str(len(self.cameraGroup.cameras)) self.ui.pushButton_saveParameter.setText('save(' + id + ')') self.cameraLists.append('Camera ' + id) self.cameraListModel.setStringList(self.cameraLists) @Slot() def saveCameraGroup(self): name = QFileDialog.getSaveFileName(self, 'Save Paramter', '../', "config (*.yml)") self.cameraGroup.saveToFile(name[0]) self.cameraLists.clear() self.cameraListModel.setStringList(self.cameraLists) ##self.cameraListModel.insertRow() @Slot() def clearGroup(self): self.cameraGroup.cameras = [] self.ui.pushButton_saveParameter.setText('save(0)') self.cameraListModel.setStringList([]) @Slot() def showCamera(self, index): cam = self.cameraGroup[index.row()] self.ui.label_showCamera.setText(str(cam)) cam.plot()
class SourceCodeManager: def __init__(self, window): self.text_edit = QtGui.QTextEdit(window) self.text_edit.setReadOnly(True) # FIXME: write an optimized model self.traceback = None self.traceback_model = QStringListModel() self.traceback_view = QListView(window) self.traceback_view.setModel(self.traceback_model) self.traceback_view.setEditTriggers( QtGui.QAbstractItemView.NoEditTriggers) window.connect( self.traceback_view.selectionModel(), QtCore.SIGNAL( "selectionChanged(const QItemSelection&, const QItemSelection&)" ), self.frame_selection_changed) # filename => (lines, mtime) self._file_cache = {} self.clear() def clear(self): self._current_file = None self._current_lineno = None self.traceback_model.setStringList([]) self.text_edit.setText('') self._file_cache.clear() def frame_selection_changed(self, selected, unselected): indexes = selected.indexes() if not indexes: return row = indexes[0].row() frame = self.traceback[row] self.show_frame(frame) def set_traceback(self, traceback, show_lineno): self.traceback = traceback if show_lineno: lines = [ '%s:%s' % (frame.filename, frame.lineno) for frame in traceback ] else: lines = [frame.filename for frame in traceback] self.traceback_model.setStringList(lines) def read_file(self, filename): try: mtime = os.stat(filename).st_mtime except OSError: return None if filename in self._file_cache: text, cache_mtime = self._file_cache[filename] if mtime == cache_mtime: return text print("Read %s content (mtime: %s)" % (filename, mtime)) with open(filename, 'rb') as fp: encoding, lines = detect_encoding(fp.readline) lineno = 1 lines = [] with io.open(filename, 'r', encoding=encoding) as fp: for lineno, line in enumerate(fp, 1): lines.append('%d: %s' % (lineno, line.rstrip())) text = '\n'.join(lines) self._file_cache[filename] = (text, mtime) return text def load_file(self, filename): if filename.startswith("<") and filename.startswith(">"): return False if self._current_file == filename: return True text = self.read_file(filename) if text is None: return False self.text_edit.setText(text) self._current_file = filename self._current_lineno = None return True def set_line_number(self, lineno): if self._current_lineno == lineno: return self._current_lineno = lineno doc = self.text_edit.document() # FIXME: complexity in O(number of lines)? block = doc.findBlockByLineNumber(lineno - 1) cursor = QTextCursor(block) cursor.select(QTextCursor.BlockUnderCursor) # FIXME: complexity in O(number of lines)? self.text_edit.setTextCursor(cursor) def show_frame(self, frame): filename = frame.filename if not self.load_file(filename): self._current_file = None self.text_edit.setText('') return if frame.lineno > 0: self.set_line_number(frame.lineno)
class Backend(QObject): textChanged = Signal(str) def __init__(self, parent=None): QObject.__init__(self, parent) self.m_text = "" self.pictureModel = PictureModel() self.keywordModel = QStringListModel() self.selectedKeywordsModel = QStringListModel() self.pictures = None self.keywords = None self.folders = [] @Property(str, notify=textChanged) def text(self): return self.m_text @text.setter def setText(self, text): # We want to get notified even if it is the same thing... right? #TODO need to handle duplicates somehow... #if self.m_text == text: # return self.m_text = text self.textChanged.emit(self.m_text) def processFolder(self, folder): folder = folder.strip("file:///") # Remove unnecessary bits if folder not in self.folders: self.folders.append(folder) #TODO get_all_pictures shouldn't overwrite what's in pictures, but add to it. self.pictures = get_all_pictures(folder) self.updateKeywordModel() #TODO keywords model? self.pictureModel.setPictureList(self.pictures) def updateKeywordModel(self): self.keywords = get_keywords(self.pictures) print(self.keywords) self.keywordModel.setStringList(self.keywords) @Slot(int, result=str) def getPicUrl(self, index): return self.pictureModel.getPicturePath(index) @Slot(result=int) def numPics(self): return self.pictureModel.rowCount(None) @Slot(str) def selectKeyword(self, keyword): print("selecting keyword: " + str(keyword)) #Only do anything if the keyword is not already in the selected list if keyword not in self.selectedKeywordsModel.stringList(): #Add keyword to selected list self.selectedKeywordsModel.setStringList( [*self.selectedKeywordsModel.stringList(), keyword]) self.filterKeywords() def filterKeywords(self): def f(x): for keyword in self.selectedKeywordsModel.stringList(): if keyword in x[2]: return True return False self.pictures = [*filter(f, self.pictures)] self.pictureModel.setPictureList(self.pictures) @Slot() def clearPics(self): #TODO is deleting the model really the best way to do this? del self.pictureModel self.pictureModel = PictureModel()
class Viewer(QObject): def __init__(self): QObject.__init__(self) self._selected_file = "" self._mask_file = "" self._selected_file_siblings = QStringListModel(self) self._supported_file_extensions = r'.png$|.jpg$' def get_selected_file(self): return self._selected_file def get_mask_file(self): return self._mask_file def get_selected_file_siblings(self): return self._selected_file_siblings def set_selected_file(self, file): if isinstance(file, QUrl): self._selected_file = file.toLocalFile() elif isinstance(file, str): self.selected_file = file self.on_selected_file.emit() # print(self._selected_file) self._detect_selected_file_siblings() def set_mask_file(self, file): if isinstance(file, QUrl): self._mask_file = file.toLocalFile() elif isinstance(file, str): self._mask_file = file self.on_mask_file.emit() @Slot(list) def set_selected_file_siblings(self, files): self._selected_file_siblings.setStringList(files) self.on_selected_file_siblings.emit() def _detect_selected_file_siblings(self): selected_file_folder = os.path.dirname(self._selected_file) temp_siblings = [] with os.scandir(selected_file_folder) as d: for entry in d: if entry.is_file() and re.search( self._supported_file_extensions, entry.name): # if entry.name != self._selected_file: file_path = os.path.abspath( os.path.join(selected_file_folder, entry.name)) temp_siblings.append(file_path) # print(temp_siblings) self.set_selected_file_siblings(temp_siblings) on_mask_file = Signal() on_selected_file = Signal() on_selected_file_siblings = Signal() mask_file = Property(QUrl, get_mask_file, set_mask_file, notify=on_mask_file) selected_file = Property(QUrl, get_selected_file, set_selected_file, notify=on_selected_file) selected_file_siblings = Property(QAbstractItemModel, get_selected_file_siblings, set_selected_file_siblings, notify=on_selected_file_siblings)
url = "http://country.io/names.json" response = urllib.request.urlopen(url) data = json.loads(response.read().decode('utf-8')) #Format and sort the data data_list = list(data.values()) data_list.sort() #Set up the application window app = QGuiApplication(sys.argv) view = QQuickView() view.setResizeMode(QQuickView.SizeRootObjectToView) #Expose the list to the Qml code my_model = QStringListModel() my_model.setStringList(data_list) view.rootContext().setContextProperty("myModel", my_model) #Load the QML file qml_file = os.path.join(os.path.dirname(__file__), "view.qml") view.setSource(QUrl.fromLocalFile(os.path.abspath(qml_file))) #Show the window if view.status() == QQuickView.Error: sys.exit(-1) view.show() #execute and cleanup app.exec_() del view
def update_possible_fields(self, possible_fields: List[str]): self.setCompleter(QCompleter()) model = QStringListModel() model.setStringList(possible_fields) self.completer().setModel(model)
class Teacher_OP(QMainWindow, TMainWindow): table_index = Signal(int) right_menu_table_index = Signal(int) time_data = Signal(int, int, int, str) def __init__(self): super(Teacher_OP, self).__init__() self.setupUi(self) self.time = 0 self.num = 0 # 记录上张表的标签数量 self.get_time_timer = QTimer(self) self.get_table_list_thread = Table_List_Get(self) self.count_timer = QTimer(self) self.clear_msg_timer = QTimer(self) self.list_model = QStringListModel() self.table_list.setModel(self.list_model) self.get_table_data_thread = Table_Data_Get(self) self.start_sign_thread = Start_Sign_IN(self) self.stop_sign_thread = Stop_Sign_IN(self) self.get_time_thread = Get_Time(self) self.delete_table_thread = Delete_Option(self) self.train_model_thread = Train_Model(self) self.creat_excel_thread = Creat_Excel(self) # chart self.series = QtCharts.QBarSeries(self) self.target_bar = QtCharts.QBarSet('学生数量') self.series.append(self.target_bar) self.axis_x = QtCharts.QBarCategoryAxis() self.axis_x.setLabelsColor(QColor(255, 0, 0)) self.axis_y = QtCharts.QValueAxis() # self.axis_y.setTitleText('人数') self.chart = QtCharts.QChart() self.chart.addSeries(self.series) self.chart.setAxisX(self.axis_x, self.series) self.chart.setAxisY(self.axis_y, self.series) self.qcv = QtCharts.QChartView(self.chart) self.init_connect() self.set_start_dis_and_set_stop_en(False) def init_connect(self): layout = QVBoxLayout() layout.addWidget(self.qcv) # 将pw加入到布局中 self.data_show_widget.setLayout(layout) self.count_timer.timeout.connect(self.time_count) self.count_timer.start(1000) self.clear_msg_timer.timeout.connect( lambda: self.show_msg_label.setText('')) self.clear_msg_timer.start(3000) self.get_time_timer.timeout.connect(self.get_time_thread.start) self.get_time_timer.start(1500) self.get_table_list_thread.table_list.connect( lambda x: self.list_model.setStringList(x)) self.get_table_list_thread.start() self.start_sign_thread.sign_msg.connect(self.set_msg) self.start_sign_thread.sign_pb_disable.connect( lambda x: self.start_sign_pb.setDisabled(x)) self.start_sign_thread.table_list_refresh.connect( self.get_table_list_thread.start) self.stop_sign_thread.res_msg.connect(self.set_msg) self.creat_excel_thread.ce_pb_disable.connect( lambda x: self.excel_creat_pb.setDisabled(x)) self.creat_excel_thread.ce_msg.connect(self.set_msg) self.get_table_data_thread.axis_x.connect(self.set_axis_x) self.get_table_data_thread.axis_y.connect(self.set_axis_y) self.get_time_thread.count_start.connect(self.get_time) self.delete_table_thread.delete_msg.connect(self.set_msg) self.delete_table_thread.table_list_refresh.connect( self.get_table_list_thread.start) self.train_model_thread.train_msg.connect(self.set_msg) self.train_model_pb.clicked.connect(self.train_model_thread.start) self.start_sign_pb.clicked.connect(lambda: self.time_data.emit( self.timeEdit.time().hour(), self.timeEdit.time().minute(), self.timeEdit.time().second(), self.course_inp_line.text())) self.stop_sign_pb.clicked.connect(self.stop_sign_thread.start) self.stop_sign_pb.clicked.connect(self.stop_sign) self.excel_creat_pb.clicked.connect(self.creat_excel_thread.start) self.table_list.clicked.connect(self.get_table_index) self.table_list.setContextMenuPolicy(Qt.CustomContextMenu) self.table_list.customContextMenuRequested[QPoint].connect( self.set_menu) def set_menu(self, _): delete_option = QMenu() delete_option.addAction( QAction("删除", delete_option, triggered=self.delete_table_thread.start)) delete_option.exec_(QCursor.pos()) def set_start_dis_and_set_stop_en(self, is_enable): self.stop_sign_pb.setDisabled(not is_enable) self.start_sign_pb.setDisabled(is_enable) def set_axis_x(self, date_list): self.axis_x.clear() self.axis_x.append(date_list) def set_axis_y(self, people_num_list): self.target_bar.remove(0, self.num) self.axis_y.setRange(0, sum(people_num_list)) self.target_bar.append(people_num_list) self.num = len(people_num_list) def set_msg(self, text): self.show_msg_label.setText(text) def get_table_index(self, index): self.table_index.emit(index.row()) def get_time(self, sec): if sec: self.count_timer.start(1000) self.time = sec self.get_time_timer.stop() def stop_sign(self): self.time = 0 def time_count(self): if self.time: self.time -= 1 self.set_start_dis_and_set_stop_en(True) else: self.count_timer.stop() self.set_start_dis_and_set_stop_en(False) self.get_time_timer.start(1500) self.show_time_label.setText( f'{str(datetime.timedelta(seconds=self.time))}') def closeEvent(self, event: QtGui.QCloseEvent) -> None: self.start_sign_thread.wait() self.get_table_data_thread.wait() self.get_table_list_thread.wait() event.accept()
class WordListDialog(QDialog): """Window to handle the edition of words in a word set""" def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle(self.tr("Edit Word set")) self.setWindowIcon(QIcon(cm.DIR_ICONS + "app.png")) box = QVBoxLayout() self.add_button = QPushButton(self.tr("Add")) self.add_file_button = QPushButton(self.tr("Add from file...")) self.del_button = QPushButton(self.tr("Remove")) self.del_button.setDisabled(True) self.save_button = QPushButton(self.tr("Save")) self.save_button.setDisabled(True) self.cancel_button = QPushButton(self.tr("Cancel")) box.addWidget(self.add_button) box.addWidget(self.del_button) box.addWidget(self.add_file_button) box.addStretch() box.addWidget(self.save_button) box.addWidget(self.cancel_button) self.view = QListView() self.model = QStringListModel() self.view.setModel(self.model) self.view.setSelectionMode(QAbstractItemView.ExtendedSelection) hlayout = QHBoxLayout() hlayout.addWidget(self.view) hlayout.addLayout(box) self.setLayout(hlayout) self.add_button.pressed.connect(self.on_add) self.del_button.pressed.connect(self.on_remove) self.add_file_button.pressed.connect(self.on_load_file) self.cancel_button.pressed.connect(self.reject) self.save_button.pressed.connect(self.accept) # Item selected in view self.view.selectionModel().selectionChanged.connect( self.on_item_selected) # Data changed in model self.model.dataChanged.connect(self.on_data_changed) self.model.rowsInserted.connect(self.on_data_changed) self.model.rowsRemoved.connect(self.on_data_changed) def on_item_selected(self, *args): """Enable the remove button when an item is selected""" self.del_button.setEnabled(True) def on_data_changed(self, *args): """Enable the save button when data in model is changed""" self.save_button.setEnabled(True) def on_add(self): """Allow to manually add a word to the list Notes: A user must click on save for the changes to take effect. """ data = self.model.stringList() data.append(self.tr("<double click to edit>")) self.model.setStringList(data) def on_remove(self): """Remove the selected rows of the list Notes: A user must click on save for the changes to take effect. """ indexes = self.view.selectionModel().selectedRows() while indexes: self.model.removeRows(indexes[0].row(), 1) indexes = self.view.selectionModel().selectedRows() self.del_button.setDisabled(True) def on_load_file(self): """Allow to automatically add words from a file See Also: :meth:`load_file` """ # Reload last directory used last_directory = QSettings().value("last_directory", QDir.homePath()) filepath, _ = QFileDialog.getOpenFileName(self, self.tr("Open Word set"), last_directory, self.tr("Text file (*.txt)")) if filepath: self.load_file(filepath) def load_file(self, filename: str): """Load file into the view Args: filename(str): A simple file with a list of words (1 per line) Current data filtering: - Strip trailing spaces and EOL characters - Skip empty lines - Skip lines with whitespaces characters (`[ \t\n\r\f\v]`) Examples: - The following line will be skipped: `"abc def\tghi\t \r\n"` - The following line will be cleaned: `"abc\r\n"` """ if not os.path.exists(filename): return # Sanitize words with open(filename, "r") as f_h: data = sanitize_words(f_h) data.update(self.model.stringList()) self.model.setStringList(list(data)) # Simulate signal... TODO: check the syntax... self.model.rowsInserted.emit(0, 0, 0)
class ControlMainWindow(QMainWindow): def __init__(self, crypter): super(ControlMainWindow, self).__init__(None) self.icon = QSystemTrayIcon() self.icon.setIcon(QtGui.QIcon('./eve_tray.png')) self.icon.show() self.setWindowIcon(QtGui.QIcon('./eve_tray.png')) self.setWindowTitle('Pve Launcher') self.ui = Ui_main_window() self.ui.setupUi(self) self.icon.activated.connect(self.activate) self.account_list_model = QStringListModel() self.ui.listView.setModel(self.account_list_model) self.login_manager = EveLoginManager(crypter) self.init_none_ui(crypter) self.settings = None self.load_settings() self.ui.txt_client_path.setText(self.settings['eve_path']) def init_none_ui(self, crypter): self.login_manager.load() acc_list = [] for account_name in self.login_manager.accounts: acc_list.append(account_name) self.account_list_model.setStringList(acc_list) version_thread = Thread(target=self.check_eve_version) version_thread.start() def load_settings(self): try: with open('pvesettings.json', 'r') as settings_file: self.settings = json.load(settings_file) except FileNotFoundError: self.settings = dict() self.settings['eve_path'] = "" def save_settings(self): with open('pvesettings.json', 'w') as settings_file: json.dump(self.settings, settings_file) def closeEvent(self, event): self.login_manager.save() self.save_settings() def changeEvent(self, event): if event.type() == QEvent.WindowStateChange: if self.windowState() & Qt.WindowMinimized: self.icon.show() QTimer.singleShot(0, self, SLOT('hide()')) event.ignore() def func_launch(self): indexes = self.ui.listView.selectedIndexes() # i get QModelIndex here for idx in indexes: try: self.login_manager.login(idx.data(), self.get_auth_code, self.get_charname, self.ui.txt_client_path.text(), self.ui.cbox_server.currentText()) except Exception as e: logger.exception('Failed to launch') invoke_in_main_thread(QMessageBox.critical, self, "Launch Error", e.__str__(), QMessageBox.Ok) def func_edit(self): indexes = self.ui.listView.selectedIndexes() # i get QModelIndex here for idx in indexes: account = self.login_manager.accounts[idx.data()] dialog = AccountDialog("Edit Account", account.login_name, account.plain_password(self.login_manager.coder), account.direct_x, account.profile_name) if dialog.show(): # result = [name, password, path, dx]: path = dialog.result[2] if not path.endswith(os.sep): path = path + os.sep account = EveAccount(dialog.result[0], dialog.result[1], self.login_manager.coder, None, None, dialog.result[3], dialog.result[2]) self.login_manager.add_account(account) def func_add(self): dialog = AccountDialog("Create Account") if dialog.show(): # [name, password, profile_name, dx] account = EveAccount(dialog.result[0], dialog.result[1], self.login_manager.coder, None, None, dialog.result[3], dialog.result[2]) self.login_manager.add_account(account) acc_list = self.account_list_model.stringList() acc_list.append(account.login_name) self.account_list_model.setStringList(acc_list) def func_delete(self): indexes = self.ui.listView.selectedIndexes() # i get QModelIndex here model = self.ui.listView.model() for idx in indexes: self.login_manager.del_account(idx.data()) model.removeRow(idx.row()) def func_clear_cache(self): self.login_manager.clear_cache() def activate(self, reason): if reason == QSystemTrayIcon.Trigger or reason == QSystemTrayIcon.DoubleClick: self.showNormal() self.raise_() self.activateWindow() # self.setWindowState(Qt.WindowNoState) # self.activateWindow() def func_browse_eve(self): folder = QDir.toNativeSeparators( QFileDialog.getExistingDirectory(None, "Eve Directory", "", QFileDialog.ShowDirsOnly)) if not folder.endswith(os.sep): folder += os.sep self.ui.txt_client_path.setText(folder) self.settings['eve_path'] = folder def check_eve_version(self): headers = {'User-Agent': EveLoginManager.useragent} #version_url = "http://client.eveonline.com/patches/premium_patchinfoTQ_inc.txt" #req = request.Request(version_url, headers=headers) #response = request.urlopen(req) #version_data = response.read().decode('utf-8') #match = re.match("BUILD:(\\d+)", version_data) server_status = EveApi.get_server_status() if server_status.version is None: return None version_string = str(server_status.version) eve_version_okay: bool = check_eve_version( version_string, self.ui.txt_client_path.text()) if not eve_version_okay: invoke_in_main_thread(QtWidgets.QMessageBox.information, self, "Eve Clients out of date", "Your eve client is out of date.", QtWidgets.QMessageBox.Ok) def set_server_status(self, text, number): self.ui.label_server_status.setText( QApplication.translate("main_window", text, None) + "({0:d})".format(number)) def get_auth_code(self, opener, request): """ :param opener: urllib.request.build_opener for sending an authcode per mail :param request: request to send using the given opener :return: the authcode """ inputDialog = QInputDialog(self) inputDialog.setInputMode(QInputDialog.TextInput) inputDialog.setCancelButtonText("Cancel") inputDialog.setLabelText("Please enter your Authcode") inputDialog.setWindowTitle("TwoFactorAuth") inputDialog.setModal(True) response = None if inputDialog.exec_() == QInputDialog.Rejected: # send mail return None, None else: return response, inputDialog.textValue().strip() inputDialog.setCancelButtonText("Cancel") if inputDialog.exec_() == QInputDialog.Rejected: return response, None return response, inputDialog.textValue().strip() def get_charname(self): """ :param mailurl: url to call for sending an authcode per mail :return: the authcode """ inputDialog = QInputDialog(self) inputDialog.setInputMode(QInputDialog.TextInput) inputDialog.setLabelText("Please enter a Charname") inputDialog.setWindowTitle("Charname Challange") inputDialog.setModal(True) if inputDialog.exec_() == QInputDialog.Rejected: return None return inputDialog.textValue().strip()
import sys from PySide2.QtCore import QUrl, QStringListModel from PySide2.QtGui import QGuiApplication from PySide2.QtQml import QQmlApplicationEngine import KillTheOld as KTO if __name__ == '__main__': app = QGuiApplication(sys.argv) model = QStringListModel() isoList = KTO.checkDirs() model.setStringList(isoList) engine = QQmlApplicationEngine() engine.rootContext().setContextProperty("myModel", model) engine.load(QUrl.fromLocalFile('view.qml')) if not engine.rootObjects(): sys.exit(-1) sys.exit(app.exec_())
class Shell(QMainWindow): def __init__(self): # constructor super().__init__() # call the parent's constructor # Test data in a model self.users = ['User 1', 'User 2', 'User 3'] self.lv_model = QStringListModel() self.lv_model.setStringList(self.users) # Create the main window content widget w = QWidget() # Setup the rest of the main window appearance self.setGeometry(300, 300, 640, 480) self.setWindowTitle('PySide2 Listview Experiments') self.setWindowIcon(QIcon('assets/icons/moon_64x64.png')) # Create and set the main layout layout = QVBoxLayout() w.setLayout(layout) # Set the layout of the main window content widget self.setCentralWidget(w) # Create and add components to the layout self.lv_label = QLabel('QListView with QStringListModel') layout.addWidget(self.lv_label) self.lv = QListView() self.lv.setSelectionMode( QListView.MultiSelection) # single selection is the default self.lv.setModel(self.lv_model) self.lv.selectionModel().selectionChanged.connect(self.item_selected) layout.addWidget(self.lv) self.button = QPushButton('Update model') self.button.clicked.connect(self.change_model) layout.addWidget(self.button) self.selected_label = QLabel('Selected item: none') layout.addWidget(self.selected_label) layout.addStretch(1) self.show() # display the UI def change_model(self): the_list = self.lv_model.stringList() the_list.append('Another User') self.lv_model.setStringList(the_list) def item_selected(self): # Get the current index (a QModelIndex object) from the QListView # From the index, get the data (a QVariant) that you can convert to a QString index = self.lv.currentIndex() # returns the primary QModelIndex indices = self.lv.selectedIndexes() # returns a list of QModelIndex selected_text = '' for i in indices: selected_text += i.data( ) + '\n' # use .data() to get the value from QModelIndex self.selected_label.setText(selected_text)
url = 'http://country.io/names.json' response = urllib.request.urlopen(url) data = json.loads(response.read()) # Format data _list = sorted(data.values()) #Setup the application window app = QApplication(sys.argv) view = QQuickView() view.setResizeMode(QQuickView.SizeRootObjectToView) url = QUrl("main.qml") # Expose a model to the Qml code my_model = QStringListModel() my_model.setStringList(_list) view.rootContext().setContextProperty('myModel', my_model) #Load the QML file view.setSource(url) # Show the window if view.status() == QQuickView.Error: sys.exit(-1) view.show() # Execute and cleanup app.exec_() del view
class Query(QMainWindow): """显示试卷和练习题的容器""" def __init__(self, record_id): super().__init__() self.record_id = record_id self.session = dbSession() # 获取答题总时间和当前题号 self.totaltime, self.current_v_question_id, self.max_num = self.load_data( ) # 使用答题已用时间初始化UI self.ui = Ui_Query(self.totaltime) self.option_model = QStringListModel() self.ui.question_panel.ui.listViewOptions.setModel(self.option_model) self.update_question() # 信号连接 self.ui.about_close.connect(self.quit_action) self.ui.question_panel.ui.pushButtonPrevious.clicked.connect( self.previous_question) self.ui.question_panel.ui.pushButtonPause.clicked.connect( self.toggle_pause_question) self.ui.question_panel.ui.pushButtonNext.clicked.connect( self.next_question) self.ui.question_panel.ui.pushButtonCommit.clicked.connect( self.commit_query) self.ui.question_panel.ui.listViewOptions.clicked.connect( self.choose_option) # TODO 能不能改进,当前index改变时 self.ui.note.textChanged.connect(self.update_note) self.ui.question_panel.ui.pushButtonChooseQuestion.clicked.connect( self.open_option_panel) def load_data(self): record = self.session.query(Record).get(self.record_id) totaltime = record.totaltime # ! 新建的试卷,此值为None current_v_question_id = record.last_v_question_id if record.max_num: max_num = record.max_num else: # 所有问题的数量 -> 最大题号 v_questions = (self.session.query(V_Question).filter_by( record_id=self.record_id).all()) max_num = len(v_questions) record.max_num = max_num self.session.commit() if not current_v_question_id: # 把此值改为record_id相同的第一个 # 记录的第一个是不是就是第一题? current_v_question_id = v_questions[0].id return totaltime, current_v_question_id, max_num def update_question(self): v_question = self.session.query(V_Question).get( self.current_v_question_id) question = self.session.query(Question).get(v_question.question_id) q = f"{question.num}. {question.question}" options = [] options.append(f"A. {question.A}") options.append(f"B. {question.B}") options.append(f"C. {question.C}") options.append(f"D. {question.D}") self.ui.question_panel.ui.textEditQuestion.setHtml(q) self.option_model.setStringList(options) # 如果这道题已经被选过答案,则阴影突出答案 record = self.session.query(Q_Record).get(v_question.id) if record: row = record.chosen index = self.option_model.index(row, 0) self.ui.question_panel.ui.listViewOptions.setCurrentIndex(index) def add_operation_time(self, operation): question_operation = Q_Operation( v_question_id=self.current_v_question_id, operation=operation, datetime=QDateTime.currentDateTime().toTime_t(), ) self.session.add(question_operation) self.session.commit() def previous_question(self): # 改变model,以改变view self.add_operation_time(OP.PREVIOUS_QUESTION) self.current_v_question_id -= 1 v_question = self.session.query(V_Question).get( self.current_v_question_id) if not v_question or v_question.record_id != self.record_id: self.current_v_question_id += self.max_num self.add_operation_time(OP.PASSIVE_START) self.update_question() def toggle_pause_question(self): if self.ui.paused: self.add_operation_time(OP.PAUSE_QUESTION) else: self.add_operation_time(OP.CONTINUE_QUESTION) def next_question(self): # 改变model,以改变view self.add_operation_time(OP.NEXT_QUESTION) self.current_v_question_id += 1 v_question = self.session.query(V_Question).get( self.current_v_question_id) if not v_question or v_question.record_id != self.record_id: self.current_v_question_id -= self.max_num self.add_operation_time(OP.PASSIVE_START) self.update_question() def choose_option(self): # 0, 1, 2, 3代表 A, B, C, D choice = self.ui.question_panel.ui.listViewOptions.currentIndex().row() q_record = self.session.query(Q_Record).get(self.current_v_question_id) if q_record: q_record.chosen = choice else: q_record = Q_Record(v_question_id=self.current_v_question_id, chosen=choice) self.session.add(q_record) self.session.commit() # print(choice) self.next_question() def open_option_panel(self): self.optionPanel = Ui_optionPanel(self.max_num) # 根据131_0的格式,131为题号,0是选项A # 找到所有已经做了的题,把答案显示出来 v_questions = (self.session.query(V_Question).filter_by( record_id=self.record_id).all()) for v_question in v_questions: v_num = v_question.v_num q_record = self.session.query(Q_Record).get(v_question.id) if q_record: chosen = q_record.chosen if chosen != -1: btn = self.optionPanel.findChild(QPushButton, f"{v_num}_{chosen}") btn.set_button_chosen() self.optionPanel.show() # 找到所有的数字按钮,把点击他们的信号连接到跳转题目 for i in range(1, self.max_num + 1): btn = self.optionPanel.findChild(QPushButton, str(i)) btn.clicked.connect(self.goto_question) for j in range(4): option_btn = self.optionPanel.findChild( QPushButton, f"{i}_{j}") # TODO 这个信号连接不太优雅 option_btn.clicked.connect(self.choose_with_option_panel) def choose_with_option_panel(self): """点击答题卡,同样db中的数据也被修改,不只是UI""" option_btn = self.sender() name = option_btn.objectName() v_num, chosen = name.split("_") v_question = (self.session.query(V_Question).filter_by( record_id=self.record_id, v_num=int(v_num)).one_or_none()) q_record = self.session.query(Q_Record).get(v_question.id) # 如果鼠标点击的按钮为选中状态,则在db中也选中该选项 # 如果鼠标点击的按钮为非选中状态,则该题没有任何选项被选中 if option_btn.isChosen: q_record.chosen = int(chosen) else: q_record.chosen = -1 self.session.commit() self.update_question() def goto_question(self): """self.sender()方法能知道调用槽函数的发送者是谁,就不再需要lambda了""" self.add_operation_time(OP.GOTO_QUESTION) btn = self.sender() v_num = int(btn.objectName()) v_question = (self.session.query(V_Question).filter_by( record_id=self.record_id, v_num=v_num).one_or_none()) self.current_v_question_id = v_question.id self.add_operation_time(OP.PASSIVE_START) self.update_question() def commit_query(self): # TODO 这个提交需要终止答题 self.add_operation_time(OP.COMMIT_QUERY) self.count_question_time() # 标记记录为完成 record = (self.session.query(Record).filter_by( id=self.record_id, is_practice=False).one_or_none()) record.finished = True self.session.commit() def count_question_time(self): # 查询所有v_questions v_questions = (self.session.query(V_Question).filter_by( record_id=self.record_id).all()) # 对于每个v_question,到Q_Operation中去查找有无operation datetimes = [] for v_question in v_questions: operations = (self.session.query(Q_Operation).filter_by( v_question_id=v_question.id).all()) if operations: datetimes = [operation.datetime for operation in operations] # 两两成对,舍去最后一位 if len(datetimes) % 2: datetimes = datetimes[:-1] total = 0 j = 0 # 将每两位的差加在一起,就是该问题的总时间 while j < len(datetimes): total += datetimes[j + 1] - datetimes[j] j += 2 q_record = self.session.query(Q_Record).get(v_question.id) q_record.question_time = total self.session.commit() def update_note(self): # TODO 能不能做题时只显示本次做题的note # TODO 交卷时显示历次的note note = self.ui.note.toPlainText() q_record = self.session.query(Q_Record).get(self.current_v_question_id) q_record.note = note self.session.commit() def quit_action(self): self.add_operation_time(OP.QUIT_QUERY) print("saveing Data into DB...") # 如果本试卷还没有交卷,则计算question_time,否则不再计算question_time record = self.session.query(Record).get(self.record_id) if not record.finished: self.count_question_time() if self.ui.totaltime is 0: # ! totaltime的单位是毫秒 self.ui.totaltime = self.ui.elapsed_time.elapsed() record.totaltime = self.ui.totaltime record.last_v_question_id = self.current_v_question_id self.session.commit()
class LabelConfigurator(QDialog): def __init__(self, boxManager, spawnPos): super().__init__() # Variables self.spawnPos = spawnPos # Objects self.boxManager = boxManager self.layout = QVBoxLayout(self) self.contentLayout = QHBoxLayout() self.settingsLayout = QVBoxLayout() self.isOccludedButton = Check('Occluded', boxManager.getRecentIsOccluded()) self.isTruncatedButton = Check('Truncated', boxManager.getRecentIsTruncated()) self.isGroupOfButton = Check('Group Of', boxManager.getRecentIsGroupOf()) self.isDepictionButton = Check('Depiction', boxManager.getRecentIsDepiction()) self.isInsideButton = Check('Inside', boxManager.getRecentIsInside()) self.acceptButton = QPushButton('Accept') self.cancelButton = QPushButton('Cancel') self.labelsModel = QStringListModel() self.labelsView = QListView() # Layout self.setWindowFlags(Qt.Popup) self.settingsLayout.setAlignment(Qt.AlignTop | Qt.AlignCenter) self.settingsLayout.setMargin(0) self.settingsLayout.addWidget(self.isOccludedButton) self.settingsLayout.addWidget(self.isTruncatedButton) self.settingsLayout.addWidget(self.isGroupOfButton) self.settingsLayout.addWidget(self.isDepictionButton) self.settingsLayout.addWidget(self.isInsideButton) self.settingsLayout.addStretch(1) self.settingsLayout.addWidget(self.acceptButton) self.settingsLayout.addWidget(self.cancelButton) self.contentLayout.addWidget(self.labelsView) self.contentLayout.addLayout(self.settingsLayout) self.layout.addLayout(self.contentLayout) # Styling self.setStyleSheet('LabelConfigurator { ' 'background-color: ' + ThemeManager.BG_L1 + ';' 'border-top-left-radius: ' + str(ThemeManager.CURVE) + 'px;' 'border-bottom-left-radius: ' + str(ThemeManager.CURVE) + 'px;' 'border-top-right-radius: ' + str(ThemeManager.CURVE) + 'px;' 'border-bottom-right-radius: ' + str(ThemeManager.CURVE) + 'px;' 'border-width: 0px;' 'border-style: solid;' '}' 'QPushButton {' 'background-color: ' + ThemeManager.BG_L2 + ';' 'border-radius: 10px;' 'color: ' + ThemeManager.LABEL + ';' 'font-size: 14px;' '}' 'QPushButton:hover {' 'background-color: ' + ThemeManager.BG_L3 + ';' '}' 'QListView { ' 'background-color: ' + ThemeManager.BG_L2 + ';' '}') self.layout.setMargin(20) self.layout.setSpacing(10) self.contentLayout.setMargin(0) self.labelsModel.setStringList(boxManager.loadLabels()) self.labelsView.setFixedWidth(80) self.labelsView.setFrameStyle(QFrame.NoFrame) self.labelsView.setModel(self.labelsModel) self.labelsView.setItemDelegate(ListDelegate.ListDelegate()) index = None try: row = self.labelsModel.stringList().index( boxManager.getRecentLabelName()) index = self.labelsModel.index(row) except ValueError: index = self.labelsModel.index(0) if index is not None: self.labelsView.setCurrentIndex(index) # Connections self.acceptButton.clicked.connect(self.close) self.cancelButton.clicked.connect(self.reject) def showEvent(self, event): super().showEvent(event) self.move(self.spawnPos) def closeEvent(self, event): labelConfig = (self.labelsView.selectedIndexes()[0].data( role=Qt.DisplayRole), self.isOccludedButton.getEnabled(), self.isTruncatedButton.getEnabled(), self.isGroupOfButton.getEnabled(), self.isDepictionButton.getEnabled(), self.isInsideButton.getEnabled()) self.labelAccepted.emit(labelConfig) super().closeEvent(event) def getLabelConfig(self): return labelAccepted = Signal(object)
class FolderViewModel: def __init__(self, parent, strFolderButtonName, strFileListViewName, strSortVendorButton="", strBurnDownButton="", strCompareBudgetButton="", strPlotMonthliesButton=""): self.parent = parent self.buttonOpenFolder = parent.findChild(QPushButton, strFolderButtonName) self.buttonOpenFolder.clicked.connect(self.FolderButtonClicked) self.ListViewFileList = parent.findChild(QListView, strFileListViewName) self.StringModelFilesList = QStringListModel([]) self.ListViewFileList.setModel(self.StringModelFilesList) self.ListViewFileList.clicked.connect(self.FileSelected) if strSortVendorButton != "": self.buttonSortVendor = parent.findChild(QPushButton, strSortVendorButton) self.buttonSortVendor.clicked.connect(self.SortByVendorClicked) if strCompareBudgetButton != "": self.buttonCompareBudget = parent.findChild( QPushButton, strCompareBudgetButton) self.buttonCompareBudget.clicked.connect(self.CompareBudgetClicked) if strBurnDownButton != "": self.buttonBurnDown = parent.findChild(QPushButton, strBurnDownButton) self.buttonBurnDown.clicked.connect(self.BurnDownClicked) if strPlotMonthliesButton != "": self.buttonPlotMonthlies = parent.findChild( QPushButton, strPlotMonthliesButton) self.buttonPlotMonthlies.clicked.connect(self.PlotMonthliesClicked) def FolderButtonClicked(self): self.strFoldername = str( QFileDialog.getExistingDirectory( self.parent, "Select Directory", "C:\\Users\\danie\\Development\\StateAnalise\\State")) self.vstrFileNames = [ os.path.basename(x) for x in glob.glob(os.path.join(self.strFoldername, "*.csv")) ] self.vtsMonthYear = list() for strFilename in self.vstrFileNames: match = re.search("\w{3}\d{4}", strFilename) if match is not None: self.vtsMonthYear.append( datetime.datetime.strptime(match[0], "%b%Y")) self.vstrFileNames = [ x for _, x in sorted(zip(self.vtsMonthYear, self.vstrFileNames)) ] self.StringModelFilesList.setStringList(self.vstrFileNames) def FileSelected(self, item): item = self.StringModelFilesList.itemData(item)[0] print("Item selected: ", item) self.strFullFilename = os.path.join(self.strFoldername, item) print(self.strFullFilename) def SortByVendorClicked(self): strFilenameToProcess = self.strFullFilename print("Sort By Vendor file: ", strFilenameToProcess) SortByVendor(strFilenameToProcess, True) def CompareBudgetClicked(self): print("Compare button clicked", self.strFullFilename) CompareBudgetWithActuals(self.strFullFilename) def BurnDownClicked(self): print("Burn Down button clicked") def PlotMonthliesClicked(self): print("Plot Monthly in directory: ", self.strFoldername) PlotStackedBarFilename(self.strFoldername)