def __init__(self): super(myWindow, self).__init__() self.myCommand = " " self.ui = Ui_MainWindow() self.ui.setupUi(self) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(16) self.ui.button = QtWidgets.QPushButton(self.ui.centralwidget) self.ui.button.setText("警报\n !!!") self.ui.button.setStyleSheet( "background-color: rgb(255, 80, 80);border-width: 1px;border-style: solid;border-color: rgb(255, 170, 150);" ) self.ui.button.setFont(font) self.ui.button.setGeometry(QtCore.QRect(900, 360, 100, 100)) self.ui.button.clicked.connect(lambda: self.on_Click1()) for i in range(0, 10): self.ui.centralwidget.findChild(QtWidgets.QPushButton, tup3[i]).clicked.connect( partial(self.open, i + 1)) for i in range(0, 38): self.ui.centralwidget.findChild( QtWidgets.QPushButton, tup2[i]).clicked.connect(partial(self.on_Clickout, i + 1)) for i in range(0, 100): self.ui.centralwidget.findChild(QtWidgets.QPushButton, tup[i]).clicked.connect( partial(self.on_Click, i + 1))
def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) ## TOGGLE/BURGUER MENU ######################################################################## self.ui.Btn_Toggle.clicked.connect( lambda: UIFunctions.toggleMenu(self, 200, True)) ## PAGES ######################################################################## # PAGE 1 # self.ui.btn_page_1.clicked.connect(lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.page_1)) # # # PAGE 2 # self.ui.btn_page_2.clicked.connect(lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.page_2)) # # # PAGE 3 # self.ui.btn_page_3.clicked.connect(lambda: self.ui.stackedWidget.setCurrentWidget(self.ui.page_3)) ## SHOW ==> MAIN WINDOW ######################################################################## self.show()
def __init__(self, dialog): Ui_MainWindow.__init__(self) self.setupUi(dialog) #Connect self.pushButton.clicked.connect(self.my_show) self.lineEdit.returnPressed.connect(self.my_show)
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) QtGui.QDialog.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.filename = None self.ui.uploadButton.clicked.connect(self.getfiles) self.ui.submitButton.clicked.connect(self.execute) self.setFixedSize(self.size())
def __init__(self): super(mywindow, self).__init__() # app settings self.ui = Ui_MainWindow() self.ui.setupUi(self) # creates a font self.font = QFont("Century Gothic", 12) self.font.setBold(True) # INITIALISATIONS self.resetGame() # disable spinners + make them listen self.ui.nbStr1.lineEdit().setReadOnly(True) self.ui.nbStr2.lineEdit().setReadOnly(True) # set my style sheet self.setFont(self.font) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.ui.payoffsTable.setItemDelegate(CenterDelegate()) # SIGNALS self.ui.nbStr1.valueChanged.connect( lambda: self.changeStrategies(self.ui.nbStr1)) self.ui.nbStr2.valueChanged.connect( lambda: self.changeStrategies(self.ui.nbStr2)) self.ui.starterButton.clicked.connect(self.lunchGame) self.ui.resetButton.clicked.connect(self.resetGame) self.activateRadios() self.ui.payoffsTable.cellChanged.connect( lambda i, j: self.changeFont(i, j, self.ui.payoffsTable)) self.ui.checkZS.stateChanged.connect(self.changeGame)
class MainWindow(QtGui.QMainWindow, Ui_MainWindow, QtGui.QWidget): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) QtGui.QDialog.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.filename = None self.ui.uploadButton.clicked.connect(self.getfiles) self.ui.submitButton.clicked.connect(self.execute) self.setFixedSize(self.size()) def getfiles(self): global img_path filename = QtGui.QFileDialog.getOpenFileName( self, 'Open file', 'c:\\', "Image files (*.jpg *.gif)") img_path = str(filename) self.ui.lineEdit.setText(filename) self.filename = filename def execute(self): if (self.filename == None): print("Filename is None") return else: message, co_ords, texts = submodules.execute_model(self.filename) self.ui.DD.setText(message) self.w = MyPopup() # self.w.setGeometry(QtCore.QRect(100, 100, 400, 200)) self.w.setWindowTitle("Output Image") write_in_image.main(img_path, co_ords, texts) label = QtGui.QLabel(self.w) pixmap = QtGui.QPixmap( "/home/vernwalrahul/my_project/Open Soft/images/final.jpg") label.setPixmap(pixmap) label.show() self.w.resize(pixmap.width(), pixmap.height()) self.w.show()
def __init__(self): super(myWindow, self).__init__() self.myCommand = " " self.ui = Ui_MainWindow() self.ui.setupUi(self) self.flag=False
class myWindow(QtWidgets.QMainWindow): def __init__(self): super(myWindow, self).__init__() self.myCommand = " " self.ui = Ui_MainWindow() self.ui.setupUi(self) self.flag=False # 五个功能函数 def openWeatherWeb(self): webbrowser.open("http://sh.weather.com.cn/") self.ui.openWeatherWeb() def openCalculator(self): os.system("calc.exe") self.ui.openCalculator() def openNotebook(self): os.system("notebook.txt") self.ui.openNotebookUi() def playMusic(self): os.system("resource\\file\\music.wav") self.ui.playMusicUi() def openWeChat(self): os.startfile("C:\Program Files (x86)\Tencent\WeChat\WeChat.exe") self.ui.openWeChat() def noCatch(self): # application.ui.notCatchUi() time.sleep(3) self.ui.notCatchUi() # 语音识别函数 def recognize_speech_from_mic(self): if not isinstance(recognizer, sr.Recognizer): raise TypeError("`recognizer` must be `Recognizer` instance") if not isinstance(microphone, sr.Microphone): raise TypeError("`microphone` must be `Microphone` instance") # 根据环境噪音调整识别器的灵敏度并记录音频 with microphone as source: recognizer.adjust_for_ambient_noise(source) audio = recognizer.listen(source) # set up the response object response = { "success": True, "error": None, "transcription": None } # 试着识别录音中的声音 # 如果RequestError或UnknownValueError异常被捕获, # 相应地更新响应对象 try: response["transcription"] = recognizer.recognize_sphinx(audio) except sr.RequestError: # API was unreachable or unresponsive# API不可达或无响应 response["success"] = False response["error"] = "API unavailable" except sr.UnknownValueError: # speech was unintelligible response["error"] = "Unable to recognize speech" return response def waitForInput(self): while True: print("recognizing") self.ui.listeningUi() guess = self.recognize_speech_from_mic() if guess["transcription"]: command=guess["transcription"] print(command) if "music" in command: self.playMusic() elif "note" in command\ or "no" in command\ or "net" in command: self.openNotebook() elif "calculator" in command\ or "counted" in command\ or "eggs" in command: self.openCalculator() elif "weather" in command \ or "whether" in command\ or "when that" in command: self.openWeatherWeb() elif "chat" in command\ or "check" in command: self.openWeChat() else: self.noCatch() if guess["error"]: print("ERROR: {}".format(guess["error"])) self.noCatch() #点击时开始识别 def mousePressEvent(self, event): if(self.flag==True): return self.flag = True global timer timer = threading.Thread(target=self.waitForInput) timer.start()
class myWindow(QtWidgets.QMainWindow): fl = 1 fl_2 = 1 def __init__(self): super(myWindow, self).__init__() self.myCommand = " " self.ui = Ui_MainWindow() self.ui.setupUi(self) font = QtGui.QFont() font.setFamily("Calibri") font.setPointSize(16) self.ui.button = QtWidgets.QPushButton(self.ui.centralwidget) self.ui.button.setText("警报\n !!!") self.ui.button.setStyleSheet( "background-color: rgb(255, 80, 80);border-width: 1px;border-style: solid;border-color: rgb(255, 170, 150);" ) self.ui.button.setFont(font) self.ui.button.setGeometry(QtCore.QRect(900, 360, 100, 100)) self.ui.button.clicked.connect(lambda: self.on_Click1()) for i in range(0, 10): self.ui.centralwidget.findChild(QtWidgets.QPushButton, tup3[i]).clicked.connect( partial(self.open, i + 1)) for i in range(0, 38): self.ui.centralwidget.findChild( QtWidgets.QPushButton, tup2[i]).clicked.connect(partial(self.on_Clickout, i + 1)) for i in range(0, 100): self.ui.centralwidget.findChild(QtWidgets.QPushButton, tup[i]).clicked.connect( partial(self.on_Click, i + 1)) def open(self, number): for i in range(1, 6): if int(number) == 2 * i - 1: lifti[i - 1].calltowait = 1 lifti[i - 1].waitcount = 1 elif int(number) == 2 * i: lifti[i - 1].calltowait = 0 lifti[i - 1].waitcount = 4 def on_Clickout(self, number): #电梯外按钮函数以及核心调度函数 self.ui.centralwidget.findChild( QtWidgets.QPushButton, tup2[number - 1] ).setStyleSheet( "background-color: rgb(255, 150, 80);border-width: 1px;border-style: solid;border-color: rgb(255, 170, 150);" ) #按钮颜色设置 self.ui.centralwidget.findChild(QtWidgets.QPushButton, tup2[number - 1]).setEnabled( False) #按下后不可再按 if number > 0 and number <= 19: #上升 self.fl = 20 - number minDic = [20, 20, 20, 20, 20] for i in range(0, 5): #按电梯距离排序 minDic[i] = abs(int(lifti[i].seat) - int(self.fl)) for i in range(0, 5): #按排序后的电梯距离顺序查找电梯 sg = minDic.index(min(minDic)) minDic[sg] = 20 if lifti[sg].notbroken and ( lifti[sg].isRest or (lifti[sg].willDown == 21 and lifti[sg].isUp and int(lifti[sg].seat) <= int(self.fl)) or (lifti[sg].willUp and lifti[sg].willUp < int(self.fl))): storeys[sg][int(self.fl) - 1] = 1 #判断该电梯是否应该响应这次按键 lifti[sg].willUp = int(self.fl) lifti[sg].willDown = 21 break elif number > 19 and number <= 38: #下降 self.fl = 40 - number minDic = [20, 20, 20, 20, 20] for i in range(0, 5): #按电梯距离排序 minDic[i] = abs(int(lifti[i].seat) - int(self.fl)) for i in range(0, 5): #按排序后的电梯距离顺序查找电梯 sg = minDic.index(min(minDic)) minDic[sg] = 20 if lifti[sg].notbroken and ( lifti[sg].isRest or (lifti[sg].willUp == 0 and lifti[sg].isDown and int(lifti[sg].seat) >= int(self.fl)) or (lifti[sg].willDown != 21 and lifti[sg].willDown > int(self.fl))): storeys[sg][int(self.fl) - 1] = 1 #判断该电梯是否应该响应这次按键 lifti[sg].willDown = int(self.fl) lifti[sg].willUp = 0 break def on_Click(self, number): self.timethread1 = timeThread(number) self.timethread1.start() self.ui.centralwidget.findChild( QtWidgets.QPushButton, tup[number - 1] ).setStyleSheet( "background-color: rgb(120, 220, 50);border-width: 1px;border-style: solid;border-color: rgb(255, 170, 0);" ) if number > 0 and number <= 20: storeys[0][20 - number] = 1 elif number > 20 and number <= 40: storeys[1][40 - number] = 1 elif number > 40 and number <= 60: storeys[2][60 - number] = 1 elif number > 60 and number <= 80: storeys[3][80 - number] = 1 elif number > 80 and number <= 100: storeys[4][100 - number] = 1 def on_Click1(self): self.ui.linelabel3.setHidden(True) self.ui.showtext() self.fl = self.ui.content if self.fl == 0: self.ui.linelabel3.setHidden(False) return 0 lifti[int(self.fl) - 1].notbroken = 0 for i in range(0, 20): self.ui.centralwidget.findChild(QtWidgets.QPushButton, tup[(int(self.fl) - 1) * 20 + i]).setEnabled(False) self.ui.centralwidget.findChild( QtWidgets.QLabel, tup1[int(self.fl) - 1] ).setStyleSheet( "border-width: 3px;border-style: solid;border-color: rgb(255, 20, 20);" )
class mywindow(QtWidgets.QMainWindow): def __init__(self): super(mywindow, self).__init__() # app settings self.ui = Ui_MainWindow() self.ui.setupUi(self) # creates a font self.font = QFont("Century Gothic", 12) self.font.setBold(True) # INITIALISATIONS self.resetGame() # disable spinners + make them listen self.ui.nbStr1.lineEdit().setReadOnly(True) self.ui.nbStr2.lineEdit().setReadOnly(True) # set my style sheet self.setFont(self.font) self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) self.ui.payoffsTable.setItemDelegate(CenterDelegate()) # SIGNALS self.ui.nbStr1.valueChanged.connect( lambda: self.changeStrategies(self.ui.nbStr1)) self.ui.nbStr2.valueChanged.connect( lambda: self.changeStrategies(self.ui.nbStr2)) self.ui.starterButton.clicked.connect(self.lunchGame) self.ui.resetButton.clicked.connect(self.resetGame) self.activateRadios() self.ui.payoffsTable.cellChanged.connect( lambda i, j: self.changeFont(i, j, self.ui.payoffsTable)) self.ui.checkZS.stateChanged.connect(self.changeGame) def changeFont(self, i, j, table): table.item(i, j).setFont(self.font) def activateRadios(self): self.ui.r1.toggled.connect(lambda: self.updateResults(self.ui.r1)) self.ui.r3.toggled.connect(lambda: self.updateResults(self.ui.r3)) # change the strategie's number of a player def changeStrategies(self, spinner): payTable = self.ui.payoffsTable value = spinner.value() if spinner.objectName() == "nbStr1": if value + 1 >= payTable.rowCount(): payTable.setRowCount(payTable.rowCount()+1) payTable.setItem( value, 0, QTableWidgetItem("Strategy " + str(value))) payTable.item(value, 0).setFont(self.font) payTable.item(value, 0).setTextAlignment( QtCore.Qt.AlignCenter) for i in range(1, payTable.columnCount()): if(not self.ui.checkZS.isChecked()): payTable.setItem(value, i, QTableWidgetItem("( , )")) else: payTable.setItem(value, i, QTableWidgetItem("")) payTable.item(value, i).setFont(self.font) else: payTable.removeRow(payTable.rowCount() - 1) else: if value + 1 >= payTable.columnCount(): payTable.setColumnCount(payTable.columnCount() + 1) payTable.setItem( 0, value, QTableWidgetItem("Strategy " + str(value))) payTable.item(0, value).setFont(self.font) payTable.item(0, value).setTextAlignment( QtCore.Qt.AlignCenter) for i in range(1, payTable.rowCount()): if(not self.ui.checkZS.isChecked()): payTable.setItem(i, value, QTableWidgetItem("( , )")) else: payTable.setItem(i, value, QTableWidgetItem("")) payTable.item(i, value).setFont(self.font) else: payTable.removeColumn(payTable.columnCount() - 1) self.alignTable() def createPayoffsTable(self, table): # setting shape table.setRowCount(2) table.setColumnCount(2) table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) table.horizontalHeader().setStretchLastSection(True) # set init cells table.setItem(0, 0, QTableWidgetItem("Player1 | Player2")) table.setItem(0, 1, QTableWidgetItem("Strategy 1")) table.setItem(1, 0, QTableWidgetItem("Strategy 1")) table.setItem(1, 1, QTableWidgetItem("")) if(not self.ui.checkZS.isChecked()): table.setItem(1, 1, QTableWidgetItem("( , )")) table.item(0, 0).setFont(self.font) table.item(0, 1).setFont(self.font) table.item(1, 0).setFont(self.font) table.item(1, 1).setFont(self.font) # rendre le 1er item inchangé item = table.item(0, 0) item.setFlags(QtCore.Qt.ItemIsEnabled) # centrer la table widget self.alignTable() def correctZeroSumProfiles(self): payTable = self.ui.payoffsTable for i in range(1, payTable.rowCount()): for j in range(1, payTable.columnCount()): profile = str(payTable.item(i, j).text()) profile = profile.replace(" ", "") regex = r'^[-+]?[0-9]+(\.[0-9]+)?$' if(not bool(re.match(regex, profile))): QMessageBox.about(self, "Error detected", "Expected an integer or a float number.\nExemple : 11.5 , 12 , 0") return False return True def correctProfiles(self): payTable = self.ui.payoffsTable for i in range(1, payTable.rowCount()): for j in range(1, payTable.columnCount()): profile = str(payTable.item(i, j).text()) profile = profile.replace(" ", "") nb_commas = profile.count(",") dec = r'[-+]?[0-9]+(\.[0-9]+)?' regex = r'^\(' + dec + r'(,'+dec+r')+\)$' if(not bool(re.match(regex, profile)) or nb_commas != 1): if(not bool(re.match(regex, profile))): QMessageBox.about(self, "Error detected", "Syntax Error at row "+str(i)) else: QMessageBox.about(self, "Error detected", "Incorrect payoffs number at row "+str(i)) return False return True def lunchGame(self): if(self.ui.checkZS.isChecked()): run = self.correctZeroSumProfiles() else: run = self.correctProfiles() if(run): str1 = [] str2 = [] profiles1 = [] profiles2 = [] payoffsTable = self.ui.payoffsTable for i in range(0, payoffsTable.rowCount()): profil1 = [] profil2 = [] # gotta get the profile of a player and convert its values to int for j in range(0, payoffsTable.columnCount()): if(i == 0 and j != 0): str2.append(payoffsTable.item(i, j).text()) if(j == 0 and i != 0): str1.append(payoffsTable.item(i, j).text()) if(i != 0 and j != 0): value = payoffsTable.item(i, j).text() value = value.replace(")", "") value = value.replace("(", "") value = value.replace(" ", "") profiles = value.split(",") if not self.ui.checkZS.isChecked(): profil1.append(float(profiles[0])) profil2.append(float(profiles[1])) else: profil1.append(float(profiles[0])) profil2.append(-float(profiles[0])) if(i != 0): profiles1.append(profil1) profiles2.append(profil2) player1 = Player(str1, np.array(profiles1)) player2 = Player(str2, np.array(profiles2)) self.game = Game([player1, player2]) # calculate nash equilibrium since it s already selected self.updateResults(self.ui.r1) # disable the profiles table + its button self.disableTable() self.ui.starterButton.setEnabled(False) self.ui.groupBox.setEnabled(True) self.ui.nbStr1.setEnabled(False) self.ui.nbStr2.setEnabled(False) self.ui.checkZS.setEnabled(False) if(self.ui.checkZS.isChecked()): self.ui.r3.setEnabled(True) else: self.ui.r3.setEnabled(False) def updateResults(self, radio): if radio.isChecked() is True: # clear the results screen self.ui.results.clear() if radio.objectName() == "r1": self.nash = self.game.supportEnumAlgo() if self.nash: for element in self.nash: self.ui.results.appendPlainText( str(tuple(self.game.players[0].strategies)) + " , " + str(tuple(self.game.players[1].strategies)) + " = " + str(element[0]) + " , " + str(element[1]) + "\n") else: self.ui.results.appendPlainText( "There's no Nash equilibrium\n") if radio.objectName() == "r3": value = self.game.calculateValue(self.nash) self.ui.results.appendPlainText( "The game's value is equal to : " + str(value) + "\n") # this will change tuples to one value def changeGame(self): table = self.ui.payoffsTable for i in range(1, table.rowCount()): for j in range(1, table.columnCount()): if self.ui.checkZS.isChecked(): table.setItem(i, j, QTableWidgetItem("")) else: table.setItem(i, j, QTableWidgetItem("( , )")) table.item(i, j).setFont(self.font) self.alignTable() def alignTable(self): table = self.ui.payoffsTable for i in range(0, table.rowCount()): for j in range(0, table.columnCount()): if(table.item(i, j)): table.item(i, j).setTextAlignment(QtCore.Qt.AlignCenter) def resetGame(self): # reset game's options self.game = None # enable widgets self.ui.nbStr1.setEnabled(True) self.ui.nbStr2.setEnabled(True) self.ui.checkZS.setEnabled(True) self.ui.checkZS.setChecked(False) self.ui.starterButton.setEnabled(True) # set strategies nb to 1 self.ui.nbStr1.setValue(1) self.ui.nbStr2.setValue(1) # disable the radios self.ui.groupBox.setEnabled(False) # clear payoff table and create it back self.ui.payoffsTable.clear() self.createPayoffsTable(self.ui.payoffsTable) # clear plain text self.ui.results.clear() def disableTable(self): table = self.ui.payoffsTable for i in range(0, table.rowCount()): for j in range(0, table.columnCount()): item = table.item(i, j) item.setFlags(QtCore.Qt.ItemIsEnabled)
def __init__(self): super(myWindow, self).__init__() self.myCommand = " " self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.widget = QtWidgets.QListWidget(self.ui.centralwidget) self.ui.widget.setGeometry(QtCore.QRect(30, 50, 700, 500)) self.ui.widget.setStyleSheet( "QListWidget{border-width: 3px;border-style: solid ;border-color: rgb(204, 232, 207);}" "QListWidget::Item{height:100px;width:670px;padding-bottom:10px;}" "QListWidget::Item:hover{border-width:0px;background:skyblue; }" "QListWidget::item:selected:!active{border-width:0px; background:lightgreen; }" ) self.ui.widget.setObjectName("widget") self.ui.widget.setContextMenuPolicy(3) self.ui.widget.customContextMenuRequested[QtCore.QPoint].connect( self.rightMenuShow) self.dirlabel = QtWidgets.QLabel(self.ui.centralwidget) self.dirlabel.setGeometry(QtCore.QRect(30, 20, 700, 30)) self.dirlabel.setFont(QFont("Roman times", 16)) self.returnbutton = QtWidgets.QPushButton(self.ui.centralwidget) self.returnbutton.setGeometry(QtCore.QRect(680, 510, 50, 40)) self.returnbutton.setStyleSheet( "border-width: 1px;border-style: solid ;border-color: rgb(0, 0, 0);" ) self.returnbutton.setText("返回") self.returnbutton.clicked.connect(self.ReturnDir) self.ui.label = QtWidgets.QLabel(self.ui.centralwidget) self.ui.label.setGeometry(QtCore.QRect(30, 600, 700, 200)) self.ui.label.setStyleSheet( "border-width: 3px;border-style: solid ;border-color: rgb(204, 232, 207);" ) self.ui.label.setObjectName("label_400") self.ui.label_200 = QtWidgets.QLabel(self.ui.centralwidget) self.ui.label_200.setAlignment(qt.AlignLeft) self.ui.label_200.setAlignment(qt.AlignTop) self.ui.label_200.setFont(QFont("Roman times", 16, QFont.Bold)) self.ui.label_200.setGeometry(QtCore.QRect(780, 50, 300, 500)) self.ui.label_200.setStyleSheet( "border-width: 3px;border-style: solid ;border-color: rgb(204, 232, 207);" ) self.ui.label_200.setObjectName("label_300") self.topFiller = QtWidgets.QWidget() self.topFiller.setStyleSheet("border-width: 0px;") self.topFiller.setMinimumSize(270, 650) self.scrolll = QtWidgets.QScrollArea(self.ui.centralwidget) self.scrolll.setGeometry(QtCore.QRect(780, 600, 300, 200)) self.scrolll.setStyleSheet( "border-width: 3px;border-style: solid ;border-color: rgb(204, 232, 207);" ) self.ShowStores() self.inputname = QtWidgets.QWidget(self.ui.centralwidget) self.inputname.setFont(QFont("Roman times", 16, QFont.Bold)) self.inputname.setGeometry(QtCore.QRect(30, 50, 700, 500)) self.nameedit1 = QtWidgets.QLineEdit(self.inputname) self.nameedit1.setGeometry(QtCore.QRect(275, 220, 150, 40)) self.nameedit1.setStyleSheet( "border-width: 1px;border-style: solid ;border-color: rgb(0, 0, 0);" ) self.nameok = QtWidgets.QPushButton(self.inputname) self.nameok.setGeometry(QtCore.QRect(275, 270, 60, 30)) self.nameok.setText("确认") self.nameok.clicked.connect(partial(self.OK, 0)) self.nameend = QtWidgets.QPushButton(self.inputname) self.nameend.setGeometry(QtCore.QRect(365, 270, 60, 30)) self.nameend.setText("取消") self.nameend.clicked.connect(partial(self.END, 0)) self.inputname.setHidden(True) self.inputfilename = QtWidgets.QWidget(self.ui.centralwidget) self.inputfilename.setFont(QFont("Roman times", 16, QFont.Bold)) self.inputfilename.setGeometry(QtCore.QRect(30, 50, 700, 500)) self.nameedit2 = QtWidgets.QLineEdit(self.inputfilename) self.nameedit2.setGeometry(QtCore.QRect(275, 220, 150, 40)) self.nameedit2.setStyleSheet( "border-width: 1px;border-style: solid ;border-color: rgb(0, 0, 0);" ) self.nameok = QtWidgets.QPushButton(self.inputfilename) self.nameok.setGeometry(QtCore.QRect(275, 270, 60, 30)) self.nameok.setText("确认") self.nameok.clicked.connect(partial(self.OK, 1)) self.nameend = QtWidgets.QPushButton(self.inputfilename) self.nameend.setGeometry(QtCore.QRect(365, 270, 60, 30)) self.nameend.setText("取消") self.nameend.clicked.connect(partial(self.END, 1)) self.inputfilename.setHidden(True) self.FileWindow = QtWidgets.QWidget(self.ui.centralwidget) self.FileWindow.setFont(QFont("Roman times", 16, QFont.Bold)) self.FileWindow.setGeometry(QtCore.QRect(30, 50, 700, 500)) self.textbox = QtWidgets.QTextEdit(self.FileWindow) self.textbox.move(30, 20) self.textbox.resize(640, 400) self.textbox.setStyleSheet( "border-width: 1px;border-style: solid ;border-color: rgb(0, 0, 0);" ) self.textbox.setFont(QFont("Roman times", 16)) self.nameok = QtWidgets.QPushButton(self.FileWindow) self.nameok.setGeometry(QtCore.QRect(80, 440, 120, 60)) self.nameok.setText("保存文件") self.nameok.clicked.connect(self.StoreFile) self.nameend = QtWidgets.QPushButton(self.FileWindow) self.nameend.setGeometry(QtCore.QRect(500, 440, 120, 60)) self.nameend.setText("取消编辑") self.nameend.clicked.connect(partial(self.END, 2)) self.FileWindow.setHidden(True) self.Load() self.Refresh() self.ShowDir()
class myWindow(QtWidgets.QMainWindow): #UI界面类 Name = [i for i in range(20)] filepointer = 0 def __init__(self): super(myWindow, self).__init__() self.myCommand = " " self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.widget = QtWidgets.QListWidget(self.ui.centralwidget) self.ui.widget.setGeometry(QtCore.QRect(30, 50, 700, 500)) self.ui.widget.setStyleSheet( "QListWidget{border-width: 3px;border-style: solid ;border-color: rgb(204, 232, 207);}" "QListWidget::Item{height:100px;width:670px;padding-bottom:10px;}" "QListWidget::Item:hover{border-width:0px;background:skyblue; }" "QListWidget::item:selected:!active{border-width:0px; background:lightgreen; }" ) self.ui.widget.setObjectName("widget") self.ui.widget.setContextMenuPolicy(3) self.ui.widget.customContextMenuRequested[QtCore.QPoint].connect( self.rightMenuShow) self.dirlabel = QtWidgets.QLabel(self.ui.centralwidget) self.dirlabel.setGeometry(QtCore.QRect(30, 20, 700, 30)) self.dirlabel.setFont(QFont("Roman times", 16)) self.returnbutton = QtWidgets.QPushButton(self.ui.centralwidget) self.returnbutton.setGeometry(QtCore.QRect(680, 510, 50, 40)) self.returnbutton.setStyleSheet( "border-width: 1px;border-style: solid ;border-color: rgb(0, 0, 0);" ) self.returnbutton.setText("返回") self.returnbutton.clicked.connect(self.ReturnDir) self.ui.label = QtWidgets.QLabel(self.ui.centralwidget) self.ui.label.setGeometry(QtCore.QRect(30, 600, 700, 200)) self.ui.label.setStyleSheet( "border-width: 3px;border-style: solid ;border-color: rgb(204, 232, 207);" ) self.ui.label.setObjectName("label_400") self.ui.label_200 = QtWidgets.QLabel(self.ui.centralwidget) self.ui.label_200.setAlignment(qt.AlignLeft) self.ui.label_200.setAlignment(qt.AlignTop) self.ui.label_200.setFont(QFont("Roman times", 16, QFont.Bold)) self.ui.label_200.setGeometry(QtCore.QRect(780, 50, 300, 500)) self.ui.label_200.setStyleSheet( "border-width: 3px;border-style: solid ;border-color: rgb(204, 232, 207);" ) self.ui.label_200.setObjectName("label_300") self.topFiller = QtWidgets.QWidget() self.topFiller.setStyleSheet("border-width: 0px;") self.topFiller.setMinimumSize(270, 650) self.scrolll = QtWidgets.QScrollArea(self.ui.centralwidget) self.scrolll.setGeometry(QtCore.QRect(780, 600, 300, 200)) self.scrolll.setStyleSheet( "border-width: 3px;border-style: solid ;border-color: rgb(204, 232, 207);" ) self.ShowStores() self.inputname = QtWidgets.QWidget(self.ui.centralwidget) self.inputname.setFont(QFont("Roman times", 16, QFont.Bold)) self.inputname.setGeometry(QtCore.QRect(30, 50, 700, 500)) self.nameedit1 = QtWidgets.QLineEdit(self.inputname) self.nameedit1.setGeometry(QtCore.QRect(275, 220, 150, 40)) self.nameedit1.setStyleSheet( "border-width: 1px;border-style: solid ;border-color: rgb(0, 0, 0);" ) self.nameok = QtWidgets.QPushButton(self.inputname) self.nameok.setGeometry(QtCore.QRect(275, 270, 60, 30)) self.nameok.setText("确认") self.nameok.clicked.connect(partial(self.OK, 0)) self.nameend = QtWidgets.QPushButton(self.inputname) self.nameend.setGeometry(QtCore.QRect(365, 270, 60, 30)) self.nameend.setText("取消") self.nameend.clicked.connect(partial(self.END, 0)) self.inputname.setHidden(True) self.inputfilename = QtWidgets.QWidget(self.ui.centralwidget) self.inputfilename.setFont(QFont("Roman times", 16, QFont.Bold)) self.inputfilename.setGeometry(QtCore.QRect(30, 50, 700, 500)) self.nameedit2 = QtWidgets.QLineEdit(self.inputfilename) self.nameedit2.setGeometry(QtCore.QRect(275, 220, 150, 40)) self.nameedit2.setStyleSheet( "border-width: 1px;border-style: solid ;border-color: rgb(0, 0, 0);" ) self.nameok = QtWidgets.QPushButton(self.inputfilename) self.nameok.setGeometry(QtCore.QRect(275, 270, 60, 30)) self.nameok.setText("确认") self.nameok.clicked.connect(partial(self.OK, 1)) self.nameend = QtWidgets.QPushButton(self.inputfilename) self.nameend.setGeometry(QtCore.QRect(365, 270, 60, 30)) self.nameend.setText("取消") self.nameend.clicked.connect(partial(self.END, 1)) self.inputfilename.setHidden(True) self.FileWindow = QtWidgets.QWidget(self.ui.centralwidget) self.FileWindow.setFont(QFont("Roman times", 16, QFont.Bold)) self.FileWindow.setGeometry(QtCore.QRect(30, 50, 700, 500)) self.textbox = QtWidgets.QTextEdit(self.FileWindow) self.textbox.move(30, 20) self.textbox.resize(640, 400) self.textbox.setStyleSheet( "border-width: 1px;border-style: solid ;border-color: rgb(0, 0, 0);" ) self.textbox.setFont(QFont("Roman times", 16)) self.nameok = QtWidgets.QPushButton(self.FileWindow) self.nameok.setGeometry(QtCore.QRect(80, 440, 120, 60)) self.nameok.setText("保存文件") self.nameok.clicked.connect(self.StoreFile) self.nameend = QtWidgets.QPushButton(self.FileWindow) self.nameend.setGeometry(QtCore.QRect(500, 440, 120, 60)) self.nameend.setText("取消编辑") self.nameend.clicked.connect(partial(self.END, 2)) self.FileWindow.setHidden(True) self.Load() self.Refresh() self.ShowDir() def closeEvent(self, a0: QtGui.QCloseEvent) -> None: self.Store() def showdirinUI(self): self.ui.label.setText(dirlist) def rightMenuShow(self): rightMenu = QMenu() removeAction = Qt.QAction( u"删除", self, triggered=self.DeleteDir ) # triggered 为右键菜单点击后的激活事件。这里slef.close调用的是系统自带的关闭事件。 gotoAction = Qt.QAction( u"打开", self, triggered=self.GotoDir ) # triggered 为右键菜单点击后的激活事件。这里slef.close调用的是系统自带的关闭事件。 addAction = Qt.QAction(u"创建文件夹", self, triggered=self.CreateDir) # 也可以指定自定义对象事件 addfileAction = Qt.QAction(u"创建文件", self, triggered=self.CreateFile) # 也可以指定自定义对象事件 rightMenu.addAction(gotoAction) rightMenu.addAction(addAction) rightMenu.addAction(addfileAction) rightMenu.addAction(removeAction) rightMenu.exec_(QtGui.QCursor.pos()) def Deleteall(self): # 格式化 store.clear() if os.path.exists("List.txt"): # 删本地文件 os.remove("List.txt") def InputName(self, NO): if NO == 0: self.inputname.setHidden(False) else: self.inputfilename.setHidden(False) def StoreFile(self): self.content = self.textbox.toPlainText() path = self.GetPath() self.count = 0 for i in path[self.filepointer][2:]: store[int(i)].clear() for j in range(10): if self.count < len(self.content): store[int(i)].append(self.content[self.count]) self.count += 1 else: break while self.count < len(self.content): manager = self.Manager( ) #这里必须用一个变量来存Manager返回的值,否则后面每次存入内存后进行的Manager会返回不同目录 if manager != -1: path[self.filepointer].append(manager) for i in range(10): if self.count < len(self.content): store[manager].append(self.content[self.count]) self.count += 1 else: break else: print("空间已满") break self.count = 0 for i in path[self.filepointer][2:]: self.count += 1 if len(store[int(i)]): continue else: length = len(path[self.filepointer]) for j in range(length - self.count - 1): path[self.filepointer].pop() self.ShowFiles() self.FileWindow.setHidden(True) self.Refresh() return True def OK(self, NO): if NO == 0: self.content = self.nameedit1.text() a = [] a.append(self.content) path = self.GetPath() for i in range(1, len(path)): if path[i][0] == self.content: return for i in range(1, len(path)): if len(path[i]) > 1: if path[i][1] == self.content: return path.append(a) self.ShowDir() self.inputname.setHidden(True) return True else: self.content = self.nameedit2.text() a = [] a.append("FILE") a.append(self.content) manager = self.Manager() if manager != -1: store[manager].append(1) a.append(manager) path = self.GetPath() for i in range(1, len(path)): if path[i][0] == self.content: return for i in range(1, len(path)): if len(path[i]) > 1: if path[i][1] == self.content: return path.append(a) self.ShowDir() self.Refresh() self.inputfilename.setHidden(True) return True def END(self, NO): if NO == 0: self.inputname.setHidden(True) elif NO == 1: self.inputfilename.setHidden(True) else: self.FileWindow.setHidden(True) return False def EveryDir(self, f, name): temp = List self.everydir(temp, f, 0, name) def everydir(self, temp, f, m, name): # 递归查找文件夹 for i in range(len(temp)): l = m if isinstance(temp[i], list): if temp[i][0] == "FILE": continue else: l += 1 if l == int(f) and temp[i][0] == name: self.ppath = temp[i] else: if l >= int(f): continue else: self.everydir(temp[i], f, l, name) def Load(self): # 初始化(从本地文件) #恢复文件列表 if os.path.exists("List.txt"): with open("List.txt", "r") as f: for s in f: s = s.split() load.append(s) for i in range(len(load)): if int(load[i][0]) == 1: if load[i][1] == '+': a = [] a.append(load[i][2]) List.append(a) else: a = [] a.append("FILE") a.append(load[i][2]) for m in load[i][3:]: a.append(m) List.append(a) if int(load[i][0]) >= int(load[i - 1][0]): floor = i while floor > 0: floor -= 1 if int(load[floor][0]) == int(load[i][0]) - 1: self.EveryDir(load[floor][0], load[floor][2]) path = self.ppath if load[i][1] == '+': a = [] a.append(load[i][2]) path.append(a) break else: a = [] a.append("FILE") a.append(load[i][2]) for m in load[i][3:]: a.append(m) path.append(a) break #恢复内存 if os.path.exists("Store.txt"): with open("Store.txt", "r") as S: count = 0 for s in S: if count < 30: s = s.split() for j in s: store[count].append(j) count += 1 def ShowStores(self): self.Storelist = [[] for i in range(30)] for i in range(30): label = QtWidgets.QLabel(self.topFiller) label.setGeometry(QtCore.QRect(0, i * 21, 20, 20)) label.setStyleSheet("border:0px;background:white") label.setText(str(i)) for j in range(1, 11): label1 = QtWidgets.QLabel(self.topFiller) label1.setGeometry(QtCore.QRect(j * 21, i * 21, 20, 20)) label1.setStyleSheet("border:0px;background:lightgreen;") label1.setText("") self.Storelist[i].append(label1) self.scrolll.setWidget(self.topFiller) def ReturnDir(self): if len(ppge): ppge.pop() self.ShowFiles() def Refresh(self): for i in range(30): length = len(store[i]) if length: for j in range(length): self.Storelist[i][j].setStyleSheet( "border:0px;background:red;") for j in range(length, 10): self.Storelist[i][j].setStyleSheet( "border:0px;background:lightgreen;") else: for j in range(10): self.Storelist[i][j].setStyleSheet( "border:0px;background:lightgreen;") def ShowFiles(self): path = self.GetPath() self.ui.widget.clear() for i in range(len(path) - 1): layout = QtWidgets.QHBoxLayout() label = QtWidgets.QLabel() label.setFont(QFont("Roman times", 16)) label.setAlignment(qt.AlignCenter) label2 = QtWidgets.QLabel() label2.setFont(QFont("Roman times", 16)) label2.setAlignment(qt.AlignCenter) label3 = QtWidgets.QLabel() widget = QtWidgets.QWidget() item = QListWidgetItem() if isinstance(path[i + 1], list): if path[i + 1][0] != "FILE": item.setText(str(path[i + 1][0])) label.setText(str(path[i + 1][0])) label.setStyleSheet("background:rgb(220,130,80) ") else: item.setText(str(path[i + 1][1])) label.setText(str(path[i + 1][1])) label.setStyleSheet("background:rgb(180,250,30) ") long = 0 for m in path[i + 1][2:]: long += len(store[int(m)]) label2.setText("Size:" + str(long)) label.setFixedSize(80, 80) label2.setFixedSize(80, 80) layout.addWidget(label) layout.addWidget(label3) layout.addWidget(label2) widget.setLayout(layout) self.ui.widget.addItem(item) self.ui.widget.setItemWidget(item, widget) txt = "Home" temp = List for i in ppge: txt += "/" txt += temp[i][0] temp = temp[i] self.dirlabel.setText(txt) def GetPath(self): # 获得当前位置 temp = List # 指针指向索引 for i in range(len(ppge)): # 根据当前位置索引在文建索引中前进 temp = temp[ppge[i]] return temp def GotoDir(self, name): # 当前位置索引更新函数 if self.ui.widget.selectedItems(): dellist = self.ui.widget.selectedItems() for delitem in dellist: del_item = self.ui.widget.takeItem(self.ui.widget.row(delitem)) name = del_item.text() path = self.GetPath() for i in range(1, len(path)): if path[i].count(name): if path[i][0] != "FILE": ppge.append(i) break else: self.txt = "" for j in path[i][2:]: for m in store[int(j)]: self.txt += str(m) self.textbox.setText(self.txt) self.filepointer = i self.FileWindow.setHidden(False) self.ShowDir() def CreateDir(self): # 创建文件夹(在当前位置) self.InputName(0) def DeleteDir(self): # 删除文件夹(按name) if self.ui.widget.selectedItems(): dellist = self.ui.widget.selectedItems() for delitem in dellist: del_item = self.ui.widget.takeItem(self.ui.widget.row(delitem)) name = del_item.text() del del_item path = self.GetPath() for i in range(1, len(path)): if path[i][0] == name: for j in path[i][1:]: self.deletedir(j) del path[i] break #这里如果不break,当你删去一个时,list长度减一但是i不减,path[i]就会越界 elif path[i][0] == "FILE": if path[i][1] == name: for m in path[i][2:]: store[int(m)].clear() del path[i] break # 这里如果不break,当你删去一个时,list长度减一但是i不减,path[i]就会越界 self.ShowDir() self.Refresh() def deletedir(self, dir): if dir[0] == "FILE": for m in dir[2:]: store[int(m)].clear() del dir else: for i in dir[1:]: self.deletedir(i) def ShowDir(self): # 显示文件表 temp = List global dirlist dirlist = "Home\n" showdir(temp, 0) # 递归 self.ui.label_200.setText(dirlist) self.ShowFiles() #文件部分 def CreateFile(self): # 创建文件 self.InputName(1) def OpenFile(self, name): self.GetPath().index(name) pass def Manager(self): for i in range(30): if len(store[i]): continue else: return i return -1 def Store(self): # 退出时保存到txt if os.path.exists("List.txt"): os.remove("List.txt") fd = open("List.txt", 'w') if os.path.exists("Store.txt"): os.remove("Store.txt") fe = open("Store.txt", 'w') for i in range(30): if len(store[i]): for j in range(len(store[i])): print(store[i][j], file=fe, end=" ") print(' ', file=fe) self.storedir(List, 0, fd) def storedir(self, temp, m, fd): # 递归保存文件列表 for i in range(len(temp)): l = m if isinstance(temp[i], list): if temp[i][0] == "FILE": print(l + 1, '-', temp[i][1], file=fd, end=" ") for j in temp[i][2:]: print(j, file=fd, end=" ") print(' ', file=fd) else: l += 1 print(l, '+', temp[i][0], file=fd) self.storedir(temp[i], l, fd)