class ChooseCatalogueList(QFrame): def __init__(self, parent): super(ChooseCatalogueList, self).__init__() self.initUI(parent) #ChooseCatalogueList() def initUI(self, parent): combo = QComboBox(self) self.title = QLabel(u'Выбор каталога:', self) self.lbl = QLabel('', self) self.descr = QLabel('', self) self.descr.setWordWrap(True) self.descr.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.onActivated(parent, parent.code_int) for x in parent.flist: combo.addItem(x['name']) combo.move(50, 50) self.title.move(5, 25) self.lbl.move(50, 100) self.descr.move(150, 50) def onact(ind): return self.onActivated(parent, ind) combo.activated[int].connect(onact) self.setAutoFillBackground(True) palette = self.palette() palette.setColor(self.backgroundRole(), QColor('white')) self.setPalette(palette) self.setFrameShape(_frameShape) self.setFrameShadow(_frameShadow) self.setLineWidth(_lineWidth) self.setMidLineWidth(_midLineWidth) #self.setGeometry(300, 300, 400, 200) #self.setWindowTitle(u'Выбор каталога') #self.show() def onActivated(self, parent, ind): text = parent.flist[ind]['fullname'] self.lbl.setText(text) self.lbl.adjustSize() text = parent.flist[ind]['comment'] self.descr.setText(text) self.descr.adjustSize() parent.code_int = ind parent.code = parent.flist[ind]['code']
class Actividad7(QWidget): def __init__(self): super().__init__() self.ventana() def ventana(self): #Etiquetas self.entrada = QLineEdit("Numero de datos", self) self.entrada.move(5,5) self.combo = QComboBox(self) self.combo.move(160,5) x= QLabel("X:", self) x.move(5,40) btn= QPushButton("Calcular", self) btn.move(190,35) y = QLabel("f(X):", self) y.move(5,70) self.entradax = QLineEdit(self) self.entradax.move(35,35) self.entraday = QLineEdit(self) self.entraday.move(35,65) btn2= QPushButton("Borrar Todo", self) btn2.move(190,65) self.valor = QLineEdit("Valor a estimar en",self) self.valor.move(5,95) self.ecuacion= QLabel("Y=",self) self.ecuacion.move(5,130) #Eventos self.entrada.textChanged[str].connect(self.combobox) self.combo.activated[str].connect(self.cambio) self.entradax.textChanged[str].connect(self.x) self.entraday.textChanged[str].connect(self.y) btn.clicked.connect(self.boton) self.entrada.selectionChanged.connect(self.sel1) self.entradax.selectionChanged.connect(self.sel2) self.entraday.selectionChanged.connect(self.sel3) self.valor.selectionChanged.connect(self.sel4) btn2.clicked.connect(self.borrar) #Ventana self.setGeometry(300, 300, 310, 150) self.setWindowTitle("Polinomios de interpolacion de Langrange") self.show() def combobox(self, text): self.combo.clear() self.entradax.clear() self.entraday.clear() if text =='': text='0' for c in range(int(text)): self.combo.addItem(str(c+1)) if len(xl)<= c: xl.append(0.0) yl.append(0.0) if text != "0": self.entradax.setText(str(xl[self.combo.currentIndex()])) self.entraday.setText(str(yl[self.combo.currentIndex()])) def cambio(self, text): self.entradax.setText(str(xl[int(text)-1])) self.entraday.setText(str(yl[int(text)-1])) def x(self, text): if text == "" or text == '-': text= "0" xl[self.combo.currentIndex()]= float(text) def y(self, text): if text == "" or text == '-': text= "0" yl[self.combo.currentIndex()]= float(text) def boton(self): if self.valor.text() == "": #Si el usuario deja en blanco el valor a conocer se conocera que es 0 self.valor.setText("0") datos= int(self.entrada.text()) #datos es el numero de datos ingresados por el usuario cx= float(self.valor.text())#cx sera el valor que el usuario quiera conocer suma=0 #Se declara la sumatoria for c in range(datos): #Este for funciona para movernos en I pro=1 #Se declara la variable producto for c2 in range(datos):#Este for funciona para movernos en J if c2!=c: #Si I es diferente a J se realizara la operacion producto pro*= (cx-xl[c2])/(xl[c]-xl[c2]) #Producto de pro*= yl[c] #Al final de pasar por cada J se multiplica por f(X) en el cual I esta actualmente suma+= pro #pro pasa a ser parte de la Sumatoria self.ecuacion.setText("Y= " + str(suma)) #Al final se imprime la Sumatoria self.ecuacion.adjustSize() def sel1(self): self.entrada.clear() def sel2(self): self.entradax.clear() def sel3(self): self.entraday.clear() def sel4(self): self.valor.clear() def borrar(self): for c in range(len(xl)): xl[c]= 0.0 yl[c]= 0.0 self.sel1() self.sel2() self.sel3() self.sel4()
class MainWindow(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.statusBar().showMessage('ready') self.filename = QLabel(self) self.filename.setText('filename') self.filename.move(20, 20) self.filename_edit = QLineEdit(self) self.filename_edit.move(80, 20) self.keywords = QLabel(self) self.keywords.setText('keyword') self.keywords.move(20, 60) self.keywords_edit = QLineEdit(self) self.keywords_edit.move(80, 60) self.button = QPushButton('search', self) self.button.move(20, 100) self.button.clicked.connect(self.search_keywords) self.setWindowModality(QtCore.Qt.ApplicationModal) self.setMaximumSize(300, 200) self.setMinimumSize(300, 200) self.setGeometry(300, 300, 300, 220) self.setWindowTitle('kws kaldi') self.error_message = QLabel(self) self.result = QLabel(self) def search_keywords(self): filename_text = self.filename_edit.text() keywords_text = self.keywords_edit.text() if filename_text == '': self.statusBar().showMessage('filename is empty!') return if not os.path.isfile(filename_text): self.statusBar().showMessage('incorrect filename!') return if keywords_text == '': self.statusBar().showMessage('keyword is empty!') return self.statusBar().showMessage('processing') process = subprocess.Popen('GST_PLUGIN_PATH=. ./transcribe-audio_TED.sh ' + str(filename_text), stdout=subprocess.PIPE, shell=True) out, err = process.communicate() print(out.decode("utf-8")) if keywords_text in out.decode("utf-8"): self.result.setText('"' + keywords_text + '"' + ' is in speech') self.result.adjustSize() else: self.result.setText('"' + keywords_text + '"' + ' is not in speech') self.result.adjustSize() self.result.move(20, 140) print(self.filename_edit.text()) self.statusBar().showMessage('ready')
def initUI(self): # self.setStyleSheet( "background-color : grey") researchLabel = QLabel('Player Name') researchLabel.setFont( QFont("Fira Mono Bold", 11)) researchLabel.adjustSize() resultsLabel = QLabel('Search results') resultsLabel.setFont( QFont("Fira Mono Bold", 11)) resultsLabel.adjustSize() researchEdit = QLineEdit() researchEdit.setStyleSheet( "border : 2px solid #75FF6961; border-radius : 5px; background-color : #cbcbcb") researchEdit.setFont( QFont("Fira Mono Bold",12)) researchEdit.returnPressed.connect(self.newResearch) grid = QGridLayout() grid.setSpacing(4) grid.addWidget(researchLabel, 1, 0) grid.addWidget(researchEdit, 1, 1) grid.addWidget(resultsLabel, 2, 0) self.setLayout(grid) # self.setGeometry(100, 100, 1000, 400) self.setWindowTitle('Player Searcher') self.show() self.researchEdit = researchEdit self.grid = grid
class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.lbl = QLabel("Ubuntu", self) combo = QComboBox(self) combo.addItem("Ubuntu") combo.addItem("Mandriva") combo.addItem("Fedora") combo.addItem("Arch") combo.addItem("Gentoo") combo.move(50, 50) self.lbl.move(50, 150) combo.activated[str].connect(self.onActivated) self.setGeometry(300, 300, 300, 200) self.setWindowTitle('QComboBox') self.show() def onActivated(self, text): self.lbl.setText(text) self.lbl.adjustSize()
def __init__(self, new_path, gallery, parent=None): super().__init__(parent) def commit(): g = utils.update_gallery_path(new_path, gallery) self.UPDATE_SIGNAL.emit(g) self.close() main_layout = QVBoxLayout() inner_layout = QHBoxLayout() title = QLabel(gallery.title) title.setWordWrap(True) title.setAlignment(Qt.AlignCenter) title.adjustSize() cover = QLabel() img = QPixmap(gallery.profile) cover.setPixmap(img) text = QLabel("The path to this gallery has been renamed\n"+ "\n{}\n".format(gallery.path)+u'\u2192'+"\n{}".format(new_path)) text.setWordWrap(True) text.setAlignment(Qt.AlignCenter) button_layout = QHBoxLayout() update_btn = QPushButton('Update') update_btn.clicked.connect(commit) close_btn = QPushButton('Close') close_btn.clicked.connect(self.close) button_layout.addWidget(update_btn) button_layout.addWidget(close_btn) inner_layout.addWidget(cover) inner_layout.addWidget(text) main_layout.addWidget(title) main_layout.addLayout(inner_layout) main_layout.addLayout(button_layout) self.main_widget.setLayout(main_layout) self.show()
class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.lbl = QLabel(self) qle = QLineEdit(self) qle.move(60, 100) self.lbl.move(60, 40) qle.textChanged[str].connect(self.onChanged) self.setGeometry(300, 300, 280, 170) self.setWindowTitle('QLineEdit') self.show() def onChanged(self, text): self.lbl.setText(text) self.lbl.adjustSize()
class Example(QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): # hbox = QHBoxLayout(self) # # pixmap = QPixmap("11.jpg") # lbl1 = QLabel(self) # lbl1.setPixmap(pixmap) # topleft = QFrame(self) # topleft.setFrameShape(QFrame.StyledPanel) # topright = QFrame(self) # topright.setFrameShape(QFrame.StyledPanel) # bottom = QFrame(self) # bottom.setFrameShape(QFrame.StyledPanel) # # spllitter1 = QSplitter(Qt.Horizontal) # spllitter1.addWidget(topleft) # spllitter1.addWidget(topright) # spllitter2 = QSplitter(Qt.Vertical) # spllitter2.addWidget(spllitter1) # spllitter2.addWidget(lbl1) # # hbox.addWidget(spllitter2) # self.setLayout(hbox) # 标签 文字 self.lbl2 = QLabel(self) qle = QLineEdit(self) qle.move(10, 40) self.lbl2.move(10, 1) qle.textChanged[str].connect(self.onChanged) self.lbl3 = QLabel('Ubuntu',self) combo = QComboBox(self) combo.addItem('Ubuntu') combo.addItem('Madriva') combo.addItem('Fedora') combo.addItem('Arch') combo.addItem('Gentoo') combo.move(10, 70) self.lbl3.move(100, 75) combo.activated[str].connect(self.onActivated) self.setGeometry(100, 100, 300, 300) self.setWindowTitle('Widget2') self.show() def onChanged(self, text): self.lbl2.setText(text) self.lbl2.adjustSize() def onActivated(self,text): self.lbl3.setText(text) self.lbl3.adjustSize()
class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): ''' Example hbox splitter2 splitter1 topleft vbox self.lbl combo topright bottom ''' # splitter hbox = QHBoxLayout(self) topleft = QFrame(self) topleft.setFrameShape(QFrame.StyledPanel) topright = QFrame(self) topright.setFrameShape(QFrame.StyledPanel) bottom = QFrame(self) bottom.setFrameShape(QFrame.StyledPanel) splitter1 = QSplitter(Qt.Horizontal) splitter1.addWidget(topleft) splitter1.addWidget(topright) splitter2 = QSplitter(Qt.Vertical) splitter2.addWidget(splitter1) splitter2.addWidget(bottom) hbox.addWidget(splitter2) self.setLayout(hbox) # combo self.lbl = QLabel("Ubuntu", self) combo = QComboBox(self) combo.addItem("Ubuntu") combo.addItem("Mandriva") combo.addItem("Fedora") combo.addItem("Arch") combo.addItem("Gentoo") combo.activated[str].connect(self.onActivated) # put combo and label into layout into frame vbox = QVBoxLayout(topleft) vbox.addWidget(self.lbl) vbox.addWidget(combo) self.setGeometry(300, 300, 300, 200) self.setWindowTitle('QSplitter') self.show() def onActivated(self, text): self.lbl.setText(text) self.lbl.adjustSize()
class MyWindow(QWidget): trans = Translator("en", "zh") def __init__(self): super(MyWindow, self).__init__() self.closed = False # for keylogger self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) self.adjustSize() self.setWindowTitle("快速翻译工具") self.label = QLabel("<center>请输入单词</center>") self.label.setWordWrap(True) self.label.adjustSize() self.edit = QLineEdit() self.edit.returnPressed.connect(self.translateByInput) self.button = QPushButton("翻译") self.button.clicked.connect(self.translateByInput) layout = QVBoxLayout(self) layout.addWidget(self.label) layout.addWidget(self.edit) layout.addWidget(self.button) t = threading.Thread(target=self.key_detect) t.start() def closeEvent(self, event): self.closed = True event.accept() def translateByInput(self): text = self.edit.text() if not text: self.label.setText("<center>请输入单词</center>") return self.translate(text) def translateByClipboard(self): cmd = "xclip -o" text = os.popen(cmd).read().strip() if not text: self.label.setText("<center>剪切板内无数据</center>") return self.translate(text) def translate(self, text): self.label.setText("翻译中。。。") self.label.setText(MyWindow.trans.translate(text) + '\n' + text) def key_detect(self): def __detectKey(t, modifiers, keys): if (modifiers['left shift'] or modifiers['right shift']) \ and keys == '<esc>': self.translateByClipboard() keylogger.log(lambda: self.closed, __detectKey)
class PlayerWindow(QWidget): def __init__(self, playerUrl): super().__init__() self.playerUrl = playerUrl self.profile = Player.Player(playerUrl) self.initUI() def initUI(self): grid = QGridLayout() self.setLayout(grid) self.pictureLabel = QLabel() if self.profile["Complete name"] != "-": self.pictureFilename = "." + self.profile["Complete name"].lower().replace(" ","") + ".jpg" else: self.pictureFilename = "." + self.profile["Name"].lower().replace(" ","") + ".jpg" #stores player profile picture locally to be displayed in window downloadFile( self.profile["Picture"], self.pictureFilename) self.pictureLabel.setPixmap( QPixmap( self.pictureFilename)) self.pictureLabel.adjustSize() grid.addWidget(self.pictureLabel,0,0,3,3) #self.label.setGeometry(160, 40, 80, 30) index = 3 for key, value in self.profile.playerAttributes.items(): if isinstance(value, (int,str)) and key != "Picture" and key != "Value (int)": lhs = QLabel() rhs = QLabel() lhs.setText( key) rhs.setText( str(value)) grid.addWidget( lhs, index, 0, Qt.AlignTop) grid.addWidget( rhs, index, 1, Qt.AlignTop) index += 1 theGraph = ValueGraph( self.profile["Value Graph"], QWidget(self), width=5, height=4, dpi=100) grid.addWidget(theGraph, index, 0, 3, 3, Qt.AlignTop) index += 3 perfText = QLabel() grid.addWidget( perfText, index, 0, 3, 3, Qt.AlignCenter) perfText.hide() perfButton = PerformanceButton( perfText, self.playerUrl) perfButton.setText("Show %s performance data" %(self.profile["Name"])) index += 3 grid.addWidget( perfButton, index, 0, 1, 3, Qt.AlignCenter) self.setWindowTitle( self.profile["Name"]) self.show() def keyPressEvent(self, event): #closes on Esc press if event.key() == Qt.Key_Escape: self.close() def closeEvent(self, event): #deletes player profile picture local file if os.path.isfile( self.pictureFilename): os.remove( self.pictureFilename)
class GoLViewer(QMainWindow): def __init__(self, gol): super(GoLViewer, self).__init__() self.imageLabel = QLabel() #self.scrollArea = QScrollArea() #self.scrollArea.setBackgroundRole(QPalette.Dark) #self.scrollArea.setWidget(self.imageLabel) #self.setCentralWidget(self.scrollArea) self.setCentralWidget(self.imageLabel) self.resize(500, 500) self.gol = gol self.golthread = GoLThread(self.gol) self.golthread.start() def _np_array_to_qimage(self, arr): shape = arr.shape im = QImage(arr, shape[1], shape[0], QImage.Format_ARGB32).rgbSwapped() im = im.scaledToWidth(600) return im def update(self, arr): shape = arr.shape self.imageLabel.setPixmap(QPixmap.fromImage(self._np_array_to_qimage(arr))) self.imageLabel.adjustSize() img = Image.fromarray(arr[:,:,:3], 'RGB') img.save('out.png') def keyPressEvent(self, e): if e.key() == Qt.Key_Escape: self.close() elif e.key() == Qt.Key_Up: self.gol.menu.go_up() self.gol.display() print "going up" elif e.key() == Qt.Key_Down: self.gol.menu.go_down() self.gol.display() print "going down" elif e.key() == Qt.Key_Left: pass elif e.key() == Qt.Key_Right: self.gol.menu.go_right() elif e.key() == Qt.Key_Enter or e.key() == Qt.Key_Return: print "enter" else: print e.key()
class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): # lineedit self.lbl = QLabel(self) qle = QLineEdit(self) qle.move(20, 30) self.lbl.move(20, 10) qle.textChanged[str].connect(self.onChanged) # combobox self.lbl1 = QLabel('ubuntu', self) combo = QComboBox(self) combo.addItem('ubuntu') combo.addItem('mandriva') combo.addItem('fedora') combo.addItem('arch') combo.addItem('gentoo') combo.move(20, 70) self.lbl1.move(20, 100) combo.activated[str].connect(self.onActivated) self.setGeometry(300, 300, 300, 250) self.setWindowTitle('widget 1') self.show() def onActivated(self, text): self.lbl1.setText(text) self.lbl1.adjustSize() def onChanged(self, text): self.lbl.setText(text) self.lbl.adjustSize()
def addLabels(self): msg = self.offer.msg if self.offer.gold < 0: txt = " and demands {} gold.".format(abs(self.offer.gold)) elif self.offer.gold > 0: txt = " and offers {} gold.".format(abs(self.offer.gold)) else: txt = "." if self.offer.type == "peace": msg = " offers you peace" elif self.offer.type == "alliance": msg = " offers you alliance" elif self.offer.type == "call to arms": msg = " calls you to arms in a war against" for player in self.offer.sender.enemies: msg = msg + " {}".format(player.name) msg = self.offer.sender.name + msg + txt lbl = QLabel(msg, self) lbl.adjustSize()
class Example(QWidget): def __init__(self): super().__init__() self.initUI() self.timer = QTimer(self) self.timer.timeout.connect(self.check) self.timer.setInterval(1000) self.timer.start() def check(self): print("Value is now", self.qle.value()) def initUI(self): self.lbl = QLabel(self) qle = MySpinBox(self, spinners=False) self.qle = qle qle.setKeyboardTracking(False) qle2 = MySpinBox(self) qle2.setKeyboardTracking(False) qle.move(60, 100) self.lbl.move(60, 40) qle.ubd_value_changed.connect(self.onChanged) #qle.valueChanged.connect(self.vc) #qle.editingFinished.connect(self.edf) self.setGeometry(300, 300, 280, 170) self.setWindowTitle('QSpinboxTest') self.show() def onChanged(self, int_): print("### UBD value changed", int_) self.lbl.setText(str(int_)) self.lbl.adjustSize()
class ImageViewer(QMainWindow): def __init__(self): super(ImageViewer, self).__init__() self.printer = QPrinter() self.scaleFactor = 0.0 self.imageLabel = QLabel() self.imageLabel.setBackgroundRole(QPalette.Base) self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.imageLabel.setScaledContents(True) self.scrollArea = QScrollArea() self.scrollArea.setBackgroundRole(QPalette.Dark) self.scrollArea.setWidget(self.imageLabel) self.setCentralWidget(self.scrollArea) self.createActions() self.createMenus() self.setWindowTitle("Image Viewer") self.resize(500, 400) def open(self): fileName, _ = QFileDialog.getOpenFileName(self, "Open File", QDir.currentPath()) if fileName: image = QImage(fileName) if image.isNull(): QMessageBox.information(self, "Image Viewer", "Cannot load %s." % fileName) return self.imageLabel.setPixmap(QPixmap.fromImage(image)) self.scaleFactor = 1.0 self.printAct.setEnabled(True) self.fitToWindowAct.setEnabled(True) self.updateActions() if not self.fitToWindowAct.isChecked(): self.imageLabel.adjustSize() def print_(self): dialog = QPrintDialog(self.printer, self) if dialog.exec_(): painter = QPainter(self.printer) rect = painter.viewport() size = self.imageLabel.pixmap().size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(self.imageLabel.pixmap().rect()) painter.drawPixmap(0, 0, self.imageLabel.pixmap()) def zoomIn(self): self.scaleImage(1.25) def zoomOut(self): self.scaleImage(0.8) def normalSize(self): self.imageLabel.adjustSize() self.scaleFactor = 1.0 def fitToWindow(self): fitToWindow = self.fitToWindowAct.isChecked() self.scrollArea.setWidgetResizable(fitToWindow) if not fitToWindow: self.normalSize() self.updateActions() def about(self): QMessageBox.about( self, "About Image Viewer", "<p>The <b>Image Viewer</b> example shows how to combine " "QLabel and QScrollArea to display an image. QLabel is " "typically used for displaying text, but it can also display " "an image. QScrollArea provides a scrolling view around " "another widget. If the child widget exceeds the size of the " "frame, QScrollArea automatically provides scroll bars.</p>" "<p>The example demonstrates how QLabel's ability to scale " "its contents (QLabel.scaledContents), and QScrollArea's " "ability to automatically resize its contents " "(QScrollArea.widgetResizable), can be used to implement " "zooming and scaling features.</p>" "<p>In addition the example shows how to use QPainter to " "print an image.</p>") def createActions(self): self.openAct = QAction("&Open...", self, shortcut="Ctrl+O", triggered=self.open) self.printAct = QAction("&Print...", self, shortcut="Ctrl+P", enabled=False, triggered=self.print_) self.exitAct = QAction("E&xit", self, shortcut="Ctrl+Q", triggered=self.close) self.zoomInAct = QAction("Zoom &In (25%)", self, shortcut="Ctrl++", enabled=False, triggered=self.zoomIn) self.zoomOutAct = QAction("Zoom &Out (25%)", self, shortcut="Ctrl+-", enabled=False, triggered=self.zoomOut) self.normalSizeAct = QAction("&Normal Size", self, shortcut="Ctrl+S", enabled=False, triggered=self.normalSize) self.fitToWindowAct = QAction("&Fit to Window", self, enabled=False, checkable=True, shortcut="Ctrl+F", triggered=self.fitToWindow) self.aboutAct = QAction("&About", self, triggered=self.about) self.aboutQtAct = QAction("About &Qt", self, triggered=QApplication.instance().aboutQt) def createMenus(self): self.fileMenu = QMenu("&File", self) self.fileMenu.addAction(self.openAct) self.fileMenu.addAction(self.printAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.exitAct) self.viewMenu = QMenu("&View", self) self.viewMenu.addAction(self.zoomInAct) self.viewMenu.addAction(self.zoomOutAct) self.viewMenu.addAction(self.normalSizeAct) self.viewMenu.addSeparator() self.viewMenu.addAction(self.fitToWindowAct) self.helpMenu = QMenu("&Help", self) self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) self.menuBar().addMenu(self.fileMenu) self.menuBar().addMenu(self.viewMenu) self.menuBar().addMenu(self.helpMenu) def updateActions(self): self.zoomInAct.setEnabled(not self.fitToWindowAct.isChecked()) self.zoomOutAct.setEnabled(not self.fitToWindowAct.isChecked()) self.normalSizeAct.setEnabled(not self.fitToWindowAct.isChecked()) def scaleImage(self, factor): self.scaleFactor *= factor self.imageLabel.resize(self.scaleFactor * self.imageLabel.pixmap().size()) self.adjustScrollBar(self.scrollArea.horizontalScrollBar(), factor) self.adjustScrollBar(self.scrollArea.verticalScrollBar(), factor) self.zoomInAct.setEnabled(self.scaleFactor < 3.0) self.zoomOutAct.setEnabled(self.scaleFactor > 0.333) def adjustScrollBar(self, scrollBar, factor): scrollBar.setValue( int(factor * scrollBar.value() + ((factor - 1) * scrollBar.pageStep() / 2))) def mousePressEvent(self, eventQMouseEvent): self.originQPoint = self.scrollArea.mapFrom(self, eventQMouseEvent.pos()) #self.originQPoint = eventQMouseEvent.pos() self.currentQRubberBand = QtWidgets.QRubberBand( QtWidgets.QRubberBand.Rectangle, self) self.currentQRubberBand.setGeometry( QtCore.QRect(self.originQPoint, QtCore.QSize())) self.currentQRubberBand.show() def mouseMoveEvent(self, eventQMouseEvent): self.x = int(eventQMouseEvent.x()) self.y = int(eventQMouseEvent.y()) text1 = str(self.x) text2 = str(self.y) #print(self.x,self.y) QtWidgets.QToolTip.showText(eventQMouseEvent.pos(), "X: " + text1 + " " + "Y: " + text2, self) if self.currentQRubberBand.isVisible(): self.currentQRubberBand.setGeometry( QtCore.QRect(self.originQPoint, eventQMouseEvent.pos()).normalized() & self.imageLabel.pixmap().rect()) def mouseReleaseEvent(self, eventQMouseEvent): self.currentQRubberBand.hide() currentQRect = self.currentQRubberBand.geometry() self.currentQRubberBand.deleteLater() cropQPixmap = self.imageLabel.pixmap().copy(currentQRect) cropQPixmap.save('output.png')
class Generator(QWidget): def __init__(self): super().__init__() self.initUI() # настройка интерфейса def initUI(self): # и объявление пары переменных self.b = [] self.i = 0 self.lbl1 = QLabel('', self) self.lbl1.move(190, 25) #self.lbl1.adjustSize() self.lbl11 = QLabel('Entered number:', self) self.lbl11.move(100, 25) #self.lbl11.adjustSize() self.lbl2 = QLabel('', self) self.lbl2.move(205, 65) self.lbl22 = QLabel('Generated number:', self) self.lbl22.move(100, 65) self.lbl3 = QLabel('', self) self.lbl3.move(100, 100) self.btn1 = QPushButton('Enter number', self) self.btn1.move(20, 20) self.btn1.clicked.connect(self.showDialog) self.btn2 = QPushButton('Generate', self) self.btn2.move(20, 60) self.btn2.setEnabled(False) self.btn2.clicked.connect(self.bongiorno) self.setGeometry(800, 400, 290, 150) self.setWindowTitle('Number Generator') self.show() # диалоговое окно, спрашивающее число у юзера def showDialog(self): number, ok = QInputDialog.getInt(self, 'Input Dialog', 'Enter your number:') if ok: self.lbl1.setText(str(number)) self.lbl1.adjustSize() self.btn2.setEnabled(True) self.b.clear() self.i = 0 self.lbl3.clear() # ф-ция генерирующая числа из диапазона и проверяющая число на "новизну" def bongiorno(self): number = int(self.lbl1.text()) a = random.randint(1, number) if self.i < number: while True: if a not in self.b: self.lbl2.setText(str(a)) self.b.append(a) self.lbl2.adjustSize() #self.lbl3.setText(str(self.b)) #self.lbl3.adjustSize() break else: while a in self.b: a = random.randint(1, number) self.lbl2.setText(str(a)) self.b.append(a) self.lbl2.adjustSize() #self.lbl3.setText(str(self.b)) #self.lbl3.adjustSize() break self.i += 1 else: self.lbl3.setText('Numbers are over!\nEnter new number') self.lbl3.adjustSize() self.btn2.setEnabled(False) self.i = 0 self.b.clear()
class IntroWindow: """ It's that first window with the lesser information. To load main project. """ def __init__(self): global version self.version = version self.tha = Thread(None, self.chargement) self.app = QApplication(sys.argv) self.win = QMainWindow() x, y = 800, 350 self.pos = center(x, y) self.win.setGeometry(self.pos[0], self.pos[1], x, y) self.win.setWindowTitle("TD2 Projects") self.win.setWindowFlag(Qt.FramelessWindowHint) self.win.show() self.label = QLabel(self.win) self.pixmap = QPixmap('.\\bin\\intro.png') self.label.setPixmap(self.pixmap) self.win.setCentralWidget(self.label) self.win.setWindowIcon(QIcon("./bin/icon.png")) # self.win.resize(self.pixmap.width(), self.pixmap.height()) self.label2 = QLabel(self.win) self.label2.setFont(QFont('Mangal', 11)) self.label2.setStyleSheet("color: white; font-weight: bold;") self.label2.setText("Ouverture en cours... Veuillez Patienter") self.label2.move(10, 295) self.label2.adjustSize() self.label2.show() self.tha.start() self.app.exec_() def chargement(self, time=52): a = " " for i in range(time): sleep(0.1) if i % 4 == 3: a = "..." elif i % 4 == 2: a = ".. " elif i % 4 == 1: a = ". " elif i % 4 == 0: a = " " self.label2.setText( f"Version {self.version}\nVeuillez Patienter {a}") self.label2.adjustSize() if i == time - 1: sleep(2) self.label2.setText("Ouverture en cours...") sleep(2) self.win.setVisible(False) qApp.quit()
class DropSiteWindow(QWidget): def __init__(self): super(DropSiteWindow, self).__init__() self.abstractLabel = QLabel( "This example accepts drags from other applications and " "displays the MIME types provided by the drag object.") self.abstractLabel.setWordWrap(True) self.abstractLabel.adjustSize() self.dropArea = DropArea() self.dropArea.changed.connect(self.updateFormatsTable) self.formatsTable = QTableWidget() self.formatsTable.setColumnCount(2) self.formatsTable.setEditTriggers(QAbstractItemView.NoEditTriggers) self.formatsTable.setHorizontalHeaderLabels(["Format", "Content"]) self.formatsTable.horizontalHeader().setStretchLastSection(True) self.clearButton = QPushButton("Clear") self.quitButton = QPushButton("Quit") self.buttonBox = QDialogButtonBox() self.buttonBox.addButton(self.clearButton, QDialogButtonBox.ActionRole) self.buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole) self.quitButton.pressed.connect(self.close) self.clearButton.pressed.connect(self.dropArea.clear) mainLayout = QVBoxLayout() mainLayout.addWidget(self.abstractLabel) mainLayout.addWidget(self.dropArea) mainLayout.addWidget(self.formatsTable) mainLayout.addWidget(self.buttonBox) self.setLayout(mainLayout) self.setWindowTitle("Drop Site") self.setMinimumSize(350, 500) def updateFormatsTable(self, mimeData=None): self.formatsTable.setRowCount(0) if mimeData is None: return for format in mimeData.formats(): formatItem = QTableWidgetItem(format) formatItem.setFlags(Qt.ItemIsEnabled) formatItem.setTextAlignment(Qt.AlignTop | Qt.AlignLeft) if format == 'text/plain': text = mimeData.text().strip() elif format == 'text/html': text = mimeData.html().strip() elif format == 'text/uri-list': text = " ".join([url.toString() for url in mimeData.urls()]) else: text = " ".join(["%02X" % ord(datum) for datum in mimeData.data(format)]) row = self.formatsTable.rowCount() self.formatsTable.insertRow(row) self.formatsTable.setItem(row, 0, QTableWidgetItem(format)) self.formatsTable.setItem(row, 1, QTableWidgetItem(text)) self.formatsTable.resizeColumnToContents(0)
class Ghost(QMainWindow): def __init__(self, use_title_bar=False, always_on_top=False, name=sys.argv[0], opacity=None): super().__init__() self.use_title_bar = use_title_bar self.always_on_top = always_on_top if self.use_title_bar: self.setAttribute(Qt.WA_NoSystemBackground) self.setAttribute(Qt.WA_TranslucentBackground) else: self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint) if self.always_on_top: self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint) self.name = name self.setWindowTitle(self.name) self.balloons = [] self.imageLabel = QLabel() # self.imageLabel.setAttribute(Qt.WA_MouseNoMask) self.setCentralWidget(self.imageLabel) if opacity is not None: self.setWindowOpacity(opacity) self.createActions() self.createMenus() def loadImage(self, fileName): image = QImage(fileName) assert not image.isNull() pixmap = QPixmap.fromImage(image) mask = pixmap.createMaskFromColor(QColor(image.pixel(0,0)), Qt.MaskInColor) if self.use_title_bar: pixmap.setMask(mask) self.imageLabel.setMask(mask) else: self.setMask(mask) self.imageLabel.setPixmap(pixmap) self.imageLabel.adjustSize() self.setFixedSize(image.size()) self.landOnScreen() def landOnScreen(self): screen = QApplication.screens()[0].size() self.move(self.x(), screen.height() - self.height() + self.y() - self.geometry().y()) def speak(self, text): balloon = Balloon(text, point=self.newBalloonPoint(), parent=self) def closure(ev): try: self.balloons.remove(balloon) except ValueError: pass balloon.destroyed.connect(closure) self.balloons.append(balloon) balloon.show() # before show(), the size() have not calculated yet pos = balloon.pos() - QPoint(balloon.width()/2, balloon.height()/2) if pos.x() < 0: pos.setX(0) if pos.y() < 0: pos.setY(0) screen = QApplication.screens()[0].size() - balloon.size() if screen.width() < pos.x(): pos.setX(screen.width()) if screen.height() < pos.y(): pos.setY(screen.height()) balloon.move(pos) def newBalloonPoint(self): screen = QApplication.screens()[0].size() headradius = min(self.width(), self.height()) / 2 pos = self.pos() + QPoint(headradius, headradius) tocenter = QVector2D(screen.width()/2-pos.x(), screen.height()/2-pos.y()) radorig = math.atan2(tocenter.y(), tocenter.x()) raddiff = random.gauss(0, 0.5**2)*math.pi radius = headradius * random.uniform(1.6,2.2) diff = QPoint(radius*math.cos(radorig+raddiff), radius*math.sin(radorig+raddiff)) return pos + diff def moveByName(self, name): dic = { 'left': 0, 'right': QApplication.screens()[0].size().width(), 'center': QApplication.screens()[0].size().width()/2-self.width()/2, } self.move(dic[name], self.y()) def closeEvent(self, ev): for balloon in self.balloons: balloon.close() def dropEvent(self, ev): self.landOnScreen() def mousePressEvent(self, ev): super().mousePressEvent(ev) self.dragAnchor = ev.pos() def mouseMoveEvent(self, ev): super().mouseMoveEvent(ev) if hasattr(self, 'dragAnchor'): self.move(ev.globalPos() - self.dragAnchor) def mouseReleaseEvent(self, ev): super().mouseReleaseEvent(ev) if hasattr(self, 'dragAnchor'): del self.dragAnchor self.landOnScreen() def mouseDoubleClickEvent(self, ev): super().mouseDoubleClickEvent(ev) self.close() def about(self): QMessageBox.about(self, "About This", "<p>hello world</p>") def createActions(self): self.exitAct = QAction("E&xit", self, triggered=self.close) self.aboutAct = QAction("&About", self, triggered=self.about) self.aboutQtAct = QAction("About &Qt", self, triggered=QApplication.instance().aboutQt) def createMenus(self): self.fileMenu = QMenu("&File", self) self.fileMenu.addAction(self.exitAct) self.viewMenu = QMenu("&View", self) self.helpMenu = QMenu("&Help", self) self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) self.menuBar().addMenu(self.fileMenu) self.menuBar().addMenu(self.viewMenu) self.menuBar().addMenu(self.helpMenu)
class ImageViewer(QMainWindow): def __init__(self): super(ImageViewer, self).__init__() self.printer = QPrinter() self.scaleFactor = 0.0 self.imageLabel = QLabel() self.imageLabel.setBackgroundRole(QPalette.Base) self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.imageLabel.setScaledContents(True) self.scrollArea = QScrollArea() self.scrollArea.setBackgroundRole(QPalette.Dark) self.scrollArea.setWidget(self.imageLabel) self.setCentralWidget(self.scrollArea) self.createActions() self.createMenus() self.setWindowTitle("Image Viewer") self.resize(500, 400) def open(self): fileName, _ = QFileDialog.getOpenFileName(self, "Open File", QDir.currentPath()) if fileName: image = QImage(fileName) if image.isNull(): QMessageBox.information(self, "Image Viewer", "Cannot load %s." % fileName) return self.imageLabel.setPixmap(QPixmap.fromImage(image)) self.scaleFactor = 1.0 self.printAct.setEnabled(True) self.fitToWindowAct.setEnabled(True) self.updateActions() if not self.fitToWindowAct.isChecked(): self.imageLabel.adjustSize() def print_(self): dialog = QPrintDialog(self.printer, self) if dialog.exec_(): painter = QPainter(self.printer) rect = painter.viewport() size = self.imageLabel.pixmap().size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(self.imageLabel.pixmap().rect()) painter.drawPixmap(0, 0, self.imageLabel.pixmap()) def zoomIn(self): self.scaleImage(1.25) def zoomOut(self): self.scaleImage(0.8) def normalSize(self): self.imageLabel.adjustSize() self.scaleFactor = 1.0 def fitToWindow(self): fitToWindow = self.fitToWindowAct.isChecked() self.scrollArea.setWidgetResizable(fitToWindow) if not fitToWindow: self.normalSize() self.updateActions() def about(self): QMessageBox.about(self, "About Image Viewer", "<p>The <b>Image Viewer</b> example shows how to combine " "QLabel and QScrollArea to display an image. QLabel is " "typically used for displaying text, but it can also display " "an image. QScrollArea provides a scrolling view around " "another widget. If the child widget exceeds the size of the " "frame, QScrollArea automatically provides scroll bars.</p>" "<p>The example demonstrates how QLabel's ability to scale " "its contents (QLabel.scaledContents), and QScrollArea's " "ability to automatically resize its contents " "(QScrollArea.widgetResizable), can be used to implement " "zooming and scaling features.</p>" "<p>In addition the example shows how to use QPainter to " "print an image.</p>") def createActions(self): self.openAct = QAction("&Open...", self, shortcut="Ctrl+O", triggered=self.open) self.printAct = QAction("&Print...", self, shortcut="Ctrl+P", enabled=False, triggered=self.print_) self.exitAct = QAction("E&xit", self, shortcut="Ctrl+Q", triggered=self.close) self.zoomInAct = QAction("Zoom &In (25%)", self, shortcut="Ctrl++", enabled=False, triggered=self.zoomIn) self.zoomOutAct = QAction("Zoom &Out (25%)", self, shortcut="Ctrl+-", enabled=False, triggered=self.zoomOut) self.normalSizeAct = QAction("&Normal Size", self, shortcut="Ctrl+S", enabled=False, triggered=self.normalSize) self.fitToWindowAct = QAction("&Fit to Window", self, enabled=False, checkable=True, shortcut="Ctrl+F", triggered=self.fitToWindow) self.aboutAct = QAction("&About", self, triggered=self.about) self.aboutQtAct = QAction("About &Qt", self, triggered=QApplication.instance().aboutQt) def createMenus(self): self.fileMenu = QMenu("&File", self) self.fileMenu.addAction(self.openAct) self.fileMenu.addAction(self.printAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.exitAct) self.viewMenu = QMenu("&View", self) self.viewMenu.addAction(self.zoomInAct) self.viewMenu.addAction(self.zoomOutAct) self.viewMenu.addAction(self.normalSizeAct) self.viewMenu.addSeparator() self.viewMenu.addAction(self.fitToWindowAct) self.helpMenu = QMenu("&Help", self) self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) self.menuBar().addMenu(self.fileMenu) self.menuBar().addMenu(self.viewMenu) self.menuBar().addMenu(self.helpMenu) def updateActions(self): self.zoomInAct.setEnabled(not self.fitToWindowAct.isChecked()) self.zoomOutAct.setEnabled(not self.fitToWindowAct.isChecked()) self.normalSizeAct.setEnabled(not self.fitToWindowAct.isChecked()) def scaleImage(self, factor): self.scaleFactor *= factor self.imageLabel.resize(self.scaleFactor * self.imageLabel.pixmap().size()) self.adjustScrollBar(self.scrollArea.horizontalScrollBar(), factor) self.adjustScrollBar(self.scrollArea.verticalScrollBar(), factor) self.zoomInAct.setEnabled(self.scaleFactor < 3.0) self.zoomOutAct.setEnabled(self.scaleFactor > 0.333) def adjustScrollBar(self, scrollBar, factor): scrollBar.setValue(int(factor * scrollBar.value() + ((factor - 1) * scrollBar.pageStep()/2)))
class RegisterPage (Page): def __init__(self): super().__init__() self.registerWindow() self.show() def registerWindow(self): self.defaultWindow("Register Page") self.L1 = QLabel("Register Account", self) self.L3 = QLabel("First Name : ", self) self.L4 = QLabel("Last Name :", self) self.L5 = QLabel("Age :", self) self.L6 = QLabel("Weight (lbs):", self) self.L7 = QLabel("Height (cm):", self) self.L8 = QLabel("Calories Intake/day:", self) self.button = QPushButton('Submit', self) self.button.setToolTip('Submit form') self.button.move(380,700) self.button.setStyleSheet("background-color: white; font-size: 16px") self.button.resize(300,40) self.button.clicked.connect(self.nextWindow) self.textbox = [QLineEdit(self) for i in range(6)] pos1 = (380,120) for i in range(6): self.textbox[i].move(pos1[0], pos1[1]+(i+1)*80) self.textbox[i].resize(300,40) self.textbox[i].setStyleSheet("background-color: white") self.L1.move(390,50) self.L3.move(125,200) self.L4.move(125,280) self.L5.move(125,360) self.L6.move(125,440) self.L7.move(125,520) self.L8.move(125,600) self.L1.setStyleSheet('font-size: 20pt; font-weight: bold') self.L3.setStyleSheet('font-size: 14pt') self.L4.setStyleSheet('font-size: 14pt') self.L5.setStyleSheet('font-size: 14pt') self.L6.setStyleSheet('font-size: 14pt') self.L7.setStyleSheet('font-size: 14pt') self.L8.setStyleSheet('font-size: 14pt') self.L1.adjustSize() self.L3.adjustSize() self.L4.adjustSize() self.L5.adjustSize() self.L6.adjustSize() self.L7.adjustSize() self.L8.adjustSize() def nextWindow(self): user = [] for count,input in enumerate(self.textbox): if (input.text() == ""): self.errorMessage("Invalid Input") return None if(count == 2 or count == 5): try: integer = int(input.text()) user.append(integer) except: self.errorMessage("Invalid Input") return None elif(count == 3 or count == 4): try: floating = float(input.text()) user.append(floating) except: self.errorMessage("Invalid Input") return None else: user.append(input.text()) update_user_info(cursor,user) conn.commit() self.w = WelcomePage() self.w.show() self.hide()
class YaP(QWidget): rate_url = 'poligon.info' query = '' query_list = [] res_label = '' file_path_label = '' rank = 0 file_taken = False res_list = [] file_queries = [] fname = '' r_count = 0 db_path = 'keywords.db' xls_path = 'rating.xls' yandex_limits = [ [0, 230, 0], [1, 276, 0], [2, 276, 0], [3, 276, 0], [4, 276, 0], [5, 230, 0], [6, 161, 0], [7, 92, 0], [8, 46, 0], [9, 46, 0], [10, 46, 0], [11, 46, 0], [12, 46, 0], [13, 46, 0], [14, 46, 0], [15, 46, 2], [16, 46, 0], [17, 46, 0], [18, 46, 0], [19, 46, 0], [20, 92, 0], [21, 161, 0], [22, 230, 0], [23, 240, 0] ] # req_date = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) req_date = str(datetime.now().strftime('%Y-%m-%d')) query_url = 'https://yandex.ru/search/xml?user=webmaster-poligon\ &key=03.279908682:25776a70171503eb70359c5bd5b820dc&l10n=ru\ &groupby=groups-on-page%3D100&lr=2&query=' def __init__(self): super().__init__() self.initUI() self.search_btn.clicked.connect(self.set_query) self.search_btn.clicked.connect(self.start_search) self.qfile_btn.clicked.connect(self.showOpenDialog) self.sfile_btn.clicked.connect(self.db_xls) def initUI(self): grid = QGridLayout() self.setLayout(grid) lbl = QLabel('Выбран запрос: ') grid.addWidget(lbl, 0, 0) lbl1 = QLabel('Поиск по запросу: ') grid.addWidget(lbl1, 3, 0) self.label = QLabel(self) grid.addWidget(self.label, 0, 1) self.field = QLineEdit(self) grid.addWidget(self.field, 3, 1) self.field.textChanged[str].connect(self.push_query) self.search_btn = QPushButton('Поиск') grid.addWidget(self.search_btn, 3, 2) self.qfile_btn = QPushButton('Файл запросов') grid.addWidget(self.qfile_btn, 5, 0) self.sfile_btn = QPushButton('Сохранить') grid.addWidget(self.sfile_btn, 5, 2) label_fake = QLabel() grid.addWidget(label_fake, 4, 0) label_fake1 = QLabel() grid.addWidget(label_fake1, 2, 0) self.label_done = QLabel() grid.addWidget(self.label_done, 6, 1) self.label_r = QLabel(self.res_label) grid.addWidget(self.label_r, 4, 1) self.label_fp = QLabel(self.file_path_label) grid.addWidget(self.label_fp, 5, 1) self.setGeometry(700, 350, 600, 200) self.setWindowTitle('\"YaP\" - is a Yandex ratings for Poligon.info') self.pbar = QProgressBar(self) grid.addWidget(self.pbar, 7, 1) self.timer = QBasicTimer() self.step = 0 self.show() def timerEvent(self, e): if self.step >= 100: self.timer.stop() return self.step = self.step + 1 self.pbar.setValue(self.step) def sql_con(self, res_list): conn = sqlite3.connect(self.db_path) db = conn.cursor() db.execute("select name from sqlite_master \ where type='table' and name='requests'") if db.fetchone(): for res in self.res_list: if len(self.file_queries) == 0: k = (self.query.encode('utf-8').decode('cp1251'), self.req_date,) db.execute("select * from requests \ where keyword=? and date=?", k) if db.fetchone(): db.execute("delete from requests \ where keyword=? and date=?", k) else: continue else: for q in self.file_queries: k = (q, self.req_date,) db.execute("select * from requests \ where keyword=? and date=?", k) if db.fetchone(): db.execute("delete from requests \ where keyword=? and date=?", k) else: continue db.executemany( "insert into requests values (?, ?, ?)", self.res_list) else: db.execute("create table requests (keyword, position, date)") db.executemany( "insert into requests values (?, ?, ?)", self.res_list) conn.commit() db.close() conn.close() def db_xls(self): conn = sqlite3.connect(self.db_path) db = conn.cursor() db.execute("select name from sqlite_master \ where type='table' and name='requests'") wb = Workbook() ws = wb.add_sheet('keywords') plain = easyxf('') if db.fetchone(): for r, row in enumerate(db.execute("select * from requests")): for c, col in enumerate(row): if (type(col) is int) != True: ws.write(r, c, col.encode('cp1251') .decode('utf-8'), plain) else: ws.write(r, c, col, plain) print(col) wb.save(self.xls_path) db.close() conn.close() def showOpenDialog(self): self.fname, _ = QFileDialog.getOpenFileName(self, 'Open file', 'C:\\Users\\gnato\\\ Desktop\\Igor\\progs\\\ python_progs\\YaP\\') if len(self.fname) > 0: book = xlrd.open_workbook(self.fname, 'rt', formatting_info=True) sh = book.sheet_by_index(0) else: pass for i in range(sh.nrows): self.query_list.append(sh.cell_value(i, 0)) print('query_list is: ') for l in self.query_list: print(l.encode('utf-8').decode('cp1251')) self.file_taken = True fname_chars = [] for char in self.fname: if (char == '/'): fname_chars.append('\\') else: fname_chars.append(char) win_path = ''.join(fname_chars) self.label_fp.setText(win_path) self.label_fp.adjustSize() self.start_search(self.event) def keyPressEvent(self, event): if type(event) == QKeyEvent: if event.key() == Qt.Key_Escape: self.close() elif event.key() == Qt.Key_Return: self.set_query(self) self.start_search(self) def set_query(self, event): self.query = self.field.text() self.rank = 0 self.file_queries = [] def push_query(self, query): self.label.setText(query) self.label.adjustSize() def start_search(self, event): if self.timer.isActive(): self.timer.stop() else: self.timer.start(100, self) self.label_done.setText( 'Запросы обработаны, результаты занесены в базу данных.\n\ Для сохранения в файл нажмите кнопку \"Сохранить\".') if self.file_taken: for j, item in enumerate(self.query_list): self.query = self.query_list[j] r = requests.get(self.query_url + self.query) self.r_count += 1 # функция limit() может быть вызвана только один раз # # во избежание неправильных показателей счётчика. # limit_data = limit(self.r_count, self.db_path, self.req_date) # # ########################################################### # if (limit_data[0]): result = r.text result_list = result.split('<url>') for i, item in enumerate(result_list): if self.rate_url in item: self.rank += i break self.res_list.append(( self.query.encode('utf-8').decode('cp1251'), self.rank, self.req_date,)) self.file_queries.append( self.query.encode('utf-8').decode('cp1251')) limit_resume = str(limit_data[1]) + ' - Winter is close!' else: limit_resume = str(limit_data[1]) +\ 'Hour limit is here... Wait about ' +\ str(60 - int(datetime.now().strftime('%M'))) +\ ' minuntes, please!' self.sql_con(self.res_list) print(limit_resume) print(int(datetime.now().strftime('%Y-%m-%d'))) print(int(datetime.now().strftime('%Y-%m-%d'))-1) else: r = requests.get(self.query_url + self.query) self.r_count += 1 result = r.text result_list = result.split('<url>') for i, item in enumerate(result_list): if self.rate_url in item: self.rank += i break if self.rank != 0: self.res_label = ('По запросу \"' + self.query + '\" сайт poligon.info \ находится на ' + str(self.rank) + '-й позиции.\nДата запроса : ' + self.req_date + '.') self.label_r.setText(self.res_label) self.label_r.adjustSize() self.res_list.append(( self.query.encode('utf-8').decode('cp1251'), self.rank, self.req_date,)) self.sql_con(self.res_list) else: self.res_label = ('По запросу \"' + self.query + '\" сайт poligon.info \ находится ниже 100-й позиции.\nДата запроса : ' + self.req_date + '.') self.label_r.setText(self.res_label) self.label_r.adjustSize() self.res_list.append(( self.query.encode('utf-8').decode('cp1251'), self.rank, self.req_date,)) self.sql_con(self.res_list) print('end') print(self.res_list)
class ImageViewer(QMainWindow): def __init__(self): super(ImageViewer, self).__init__() self.printer = QPrinter() self.scaleFactor = 0.0 self.imageLabel = QLabel() self.imageLabel.setBackgroundRole(QPalette.Base) self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.imageLabel.setScaledContents(True) self.scrollArea = QScrollArea() self.scrollArea.setBackgroundRole(QPalette.Dark) self.scrollArea.setWidget(self.imageLabel) self.setCentralWidget(self.scrollArea) self.createActions() self.createMenus() self.initUI() self.setWindowTitle("Encrypter Pictures") self.resize(500, 400) def initUI(self): encrypt = QAction(QIcon(CURRENT_DIR + '/encrypt.png'), 'Encrypt', self) encrypt.setShortcut('Ctrl+D') encrypt.triggered.connect(self.buttonClicked) open_file= QAction(QIcon(CURRENT_DIR + '/open.png'), 'Exit', self) open_file.triggered.connect(self.open) exitAction = QAction(QIcon(CURRENT_DIR + '/exit24.png'), 'Exit', self) exitAction.triggered.connect(qApp.quit) self.toolbar = self.addToolBar('Exit') self.toolbar.addAction(open_file) self.toolbar.addAction(encrypt) self.toolbar.addAction(exitAction) self.statusBar() def buttonClicked(self): try: self.statusBar().showMessage("Encrypting: " + self.fileName) self.output_path = cript(self.fileName) self.show_image() self.statusBar().showMessage("Salve on: " + self.output_path) except AttributeError: self.statusBar().showMessage("Select an image") def show_image(self): """docstring for show_image""" if self.output_path: image = QImage(self.output_path) if image.isNull(): QMessageBox.information(self, "Image Viewer", "Cannot load %s." % self.output_path) return self.imageLabel.setPixmap(QPixmap.fromImage(image)) self.scaleFactor = 1.0 self.printAct.setEnabled(True) self.fitToWindowAct.setEnabled(True) self.updateActions() if not self.fitToWindowAct.isChecked(): self.imageLabel.adjustSize() def open(self): self.fileName, _ = QFileDialog.getOpenFileName(self, "Open File", QDir.currentPath()) if self.fileName: image = QImage(self.fileName) if image.isNull(): QMessageBox.information(self, "Image Viewer", "Cannot load %s." % self.fileName) return self.imageLabel.setPixmap(QPixmap.fromImage(image)) self.scaleFactor = 1.0 self.printAct.setEnabled(True) self.fitToWindowAct.setEnabled(True) self.updateActions() if not self.fitToWindowAct.isChecked(): self.imageLabel.adjustSize() def print_(self): dialog = QPrintDialog(self.printer, self) if dialog.exec_(): painter = QPainter(self.printer) rect = painter.viewport() size = self.imageLabel.pixmap().size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport( rect.x(), rect.y(), size.width(), size.height() ) painter.setWindow(self.imageLabel.pixmap().rect()) painter.drawPixmap(0, 0, self.imageLabel.pixmap()) def zoomIn(self): self.scaleImage(1.25) def zoomOut(self): self.scaleImage(0.8) def normalSize(self): self.imageLabel.adjustSize() self.scaleFactor = 1.0 def fitToWindow(self): fitToWindow = self.fitToWindowAct.isChecked() self.scrollArea.setWidgetResizable(fitToWindow) if not fitToWindow: self.normalSize() self.updateActions() def about(self): QMessageBox.about(self, "About Encrypter Pictures", "<p>The <b>Encrypter Pictures</b> is a software to encrypt and" "decrypting any given image") def createActions(self): self.openAct = QAction( QIcon(CURRENT_DIR + '/open.png'), "&Open...", self, shortcut="Ctrl+O", triggered=self.open ) self.printAct = QAction( QIcon(CURRENT_DIR + '/print.png'), "&Print...", self, shortcut="Ctrl+P", enabled=False, triggered=self.print_ ) self.exitAct = QAction( QIcon(CURRENT_DIR + '/exit24.png'), "E&xit", self, shortcut="Ctrl+Q", triggered=self.close ) self.zoomInAct = QAction( QIcon(CURRENT_DIR + '/zoom_in.png'), "Zoom &In (25%)", self, shortcut="Ctrl++", enabled=False, triggered=self.zoomIn ) self.zoomOutAct = QAction( QIcon(CURRENT_DIR + '/zoom_out.png'), "Zoom &Out (25%)", self, shortcut="Ctrl+-", enabled=False, triggered=self.zoomOut ) self.normalSizeAct = QAction( QIcon(CURRENT_DIR + '/zoom.png'), "&Normal Size", self, shortcut="Ctrl+S", enabled=False, triggered=self.normalSize ) self.fitToWindowAct = QAction( QIcon(CURRENT_DIR + '/expand.png'), "&Fit to Window", self, enabled=False, checkable=True, shortcut="Ctrl+F", triggered=self.fitToWindow ) self.aboutAct = QAction( QIcon(CURRENT_DIR + '/info.png'), "&About", self, triggered=self.about ) self.aboutQtAct = QAction( QIcon(CURRENT_DIR + '/pyqt.png'), "About &Qt", self, triggered=QApplication.instance().aboutQt ) def createMenus(self): self.fileMenu = QMenu("&File", self) self.fileMenu.addAction(self.openAct) self.fileMenu.addAction(self.printAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.exitAct) self.viewMenu = QMenu("&View", self) self.viewMenu.addAction(self.zoomInAct) self.viewMenu.addAction(self.zoomOutAct) self.viewMenu.addAction(self.normalSizeAct) self.viewMenu.addSeparator() self.viewMenu.addAction(self.fitToWindowAct) self.helpMenu = QMenu("&Help", self) self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) self.menuBar().addMenu(self.fileMenu) self.menuBar().addMenu(self.viewMenu) self.menuBar().addMenu(self.helpMenu) def updateActions(self): self.zoomInAct.setEnabled(not self.fitToWindowAct.isChecked()) self.zoomOutAct.setEnabled(not self.fitToWindowAct.isChecked()) self.normalSizeAct.setEnabled(not self.fitToWindowAct.isChecked()) def scaleImage(self, factor): self.scaleFactor *= factor self.imageLabel.resize(self.scaleFactor * self.imageLabel.pixmap().size()) self.adjustScrollBar(self.scrollArea.horizontalScrollBar(), factor) self.adjustScrollBar(self.scrollArea.verticalScrollBar(), factor) self.zoomInAct.setEnabled(self.scaleFactor < 3.0) self.zoomOutAct.setEnabled(self.scaleFactor > 0.333) def adjustScrollBar(self, scrollBar, factor): scrollBar.setValue(int(factor * scrollBar.value() + ((factor - 1) * scrollBar.pageStep()/2)))
class HomeRecommendedItem(QWidget, fc_home_recommended_item): """ This class represents a HomeRecommendedItem widget which is shown on the home page. This widget can either show a channel or a torrent. """ def __init__(self, parent): QWidget.__init__(self, parent) fc_home_recommended_item.__init__(self) self.setupUi(self) self.show_torrent = True self.torrent_info = None self.channel_info = None self.download_uri = None self.dialog = None # Create the category label, shown on cells that display a torrent on the home page self.category_label = QLabel(self) self.category_label.setFixedHeight(24) self.category_label.setSizePolicy(QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)) self.category_label.setStyleSheet(""" border: 2px solid white; border-radius: 12px; background-color: transparent; color: white; padding-left: 4px; padding-right: 4px; font-weight: bold; """) self.category_label.move(QPoint(6, 6)) self.category_label.show() # Create the dark overlay and download button over the thumbnail on hover self.dark_overlay = QWidget(self) self.dark_overlay.setStyleSheet("background-color: rgba(0, 0, 0, 0.65);") self.dark_overlay.hide() self.download_button = QToolButton(self) self.download_button.setFixedSize(QSize(40, 40)) self.download_button.setStyleSheet(""" QToolButton { background-color: transparent; border: 2px solid white; border-radius: 20px; } QToolButton::hover { border: 2px solid #B5B5B5; } """) self.download_button.setIcon(QIcon(get_image_path('downloads.png'))) self.download_button.setIconSize(QSize(18, 18)) self.download_button.clicked.connect(self.on_download_button_clicked) self.download_button.hide() def on_download_button_clicked(self): if not self.torrent_info: return self.download_uri = (u"magnet:?xt=urn:btih:%s&dn=%s" % (self.torrent_info["infohash"], self.torrent_info['name'])).encode('utf-8') self.window().start_download_from_uri(self.download_uri) def update_with_torrent(self, torrent): if not torrent: return self.show_torrent = True self.torrent_info = torrent self.thumbnail_widget.initialize(torrent["name"], HOME_ITEM_FONT_SIZE) self.main_label.setText(torrent["name"]) self.category_label.setText(torrent["category"].lower()) self.category_label.adjustSize() self.category_label.setHidden(False) self.setCursor(Qt.ArrowCursor) self.detail_label.setText("Size: " + format_size(torrent["size"])) def update_with_channel(self, channel): if not channel: return self.show_torrent = False self.channel_info = channel self.thumbnail_widget.initialize(channel["name"], HOME_ITEM_FONT_SIZE) self.main_label.setText(channel["name"]) self.detail_label.setText("Updated " + pretty_date(channel["modified"])) self.category_label.setHidden(True) self.setCursor(Qt.PointingHandCursor) def enterEvent(self, _): if self.show_torrent: self.dark_overlay.resize(self.thumbnail_widget.size()) self.dark_overlay.show() self.download_button.move((self.thumbnail_widget.width() - self.download_button.width()) / 2, (self.thumbnail_widget.height() - self.download_button.height()) / 2) self.download_button.show() def leaveEvent(self, _): self.dark_overlay.hide() self.download_button.hide()
def initUI(self): targetButton = QPushButton('Select Target', self) targetButton.setToolTip('Select midi you want suggestions for') targetButton.resize(targetButton.sizeHint()) targetButton.clicked.connect(self.picktargetmidi) self.inputlistview = QListWidget() self.inputlistview.itemPressed.connect(self.showmidi) inputlistview_lbl = QLabel(self) inputlistview_lbl.setText("Input MIDIs") inputlistview_lbl.adjustSize() suggestionlistview_lbl = QLabel(self) suggestionlistview_lbl.setText("Suggested segments") suggestionlistview_lbl.adjustSize() self.target_lbl = QLabel(self) self.target_lbl.setText("Please select target midi") self.target_lbl.adjustSize() self.suggestionlistview = QListWidget() suggestButton = QPushButton("Suggest", self) suggestButton.setToolTip('Suggest a continuation to target midi') suggestButton.clicked.connect(self.suggestmidi) saveButton = QPushButton("Save Suggestions", self) importAction = QAction(self.tr('Add MIDI file(s)'), self) importAction.setShortcut('Ctrl+O') importAction.setStatusTip('Add MIDI files to pool') importAction.triggered.connect(self.pickfiles) hbox = QHBoxLayout() hbox.addStretch(1) hbox.addWidget(self.target_lbl) hbox.addWidget(targetButton) hbox.addWidget(suggestButton) hbox.addWidget(saveButton) vbox = QVBoxLayout() vbox.addStretch(1) vbox.addWidget(inputlistview_lbl) vbox.addWidget(self.inputlistview) vbox.addLayout(hbox) vbox.addWidget(suggestionlistview_lbl) vbox.addWidget(self.suggestionlistview) cwidget = QWidget() cwidget.setLayout(vbox) self.setCentralWidget(cwidget) self.statusBar().showMessage('Ready') self.statusBar() menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(importAction) self.center() self.setGeometry(150,20,100,100) self.setWindowTitle('Gnotestic') self.show()
class ImageViewer(QMainWindow): def __init__(self): super(ImageViewer, self).__init__() self.printer = QPrinter() self.scaleFactor = 0.0 self.imageLabel = QLabel() self.imageLabel.setBackgroundRole(QPalette.Base) self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.imageLabel.setScaledContents(True) self.scrollArea = QScrollArea() self.scrollArea.setBackgroundRole(QPalette.Dark) self.scrollArea.setWidget(self.imageLabel) self.setCentralWidget(self.scrollArea) self.createActions() self.createMenus() self.setWindowTitle("Retinopathy") self.resize(500, 400) def open(self): fileName, _ = QFileDialog.getOpenFileName(self, "Open File", QDir.currentPath()) if fileName: image = QImage(fileName) if image.isNull(): QMessageBox.information(self, "Retinopathy", "Cannot load %s." % fileName) return self.imageLabel.setPixmap(QPixmap.fromImage(image)) self.scaleFactor = 1.0 self.printAct.setEnabled(True) self.fitToWindowAct.setEnabled(True) self.updateActions() if not self.fitToWindowAct.isChecked(): self.imageLabel.adjustSize() DENSENET_121_WEIGHTS_PATH_NO_TOP = ( r'https://github.com/titu1994/DenseNet/releases/' r'download/v3.0/DenseNet-BC-121-32-no-top.h5') densenet = DenseNet121(weights=get_file( 'DenseNet-BC-121-32-no-top.h5', DENSENET_121_WEIGHTS_PATH_NO_TOP, cache_subdir='models', md5_hash='55e62a6358af8a0af0eedf399b5aea99'), include_top=False, input_shape=(224, 224, 3)) def build_model(): model = Sequential() model.add(densenet) model.add(layers.GlobalAveragePooling2D()) model.add(layers.Dropout(0.5)) model.add(layers.Dense(5, activation='sigmoid')) return model model = build_model() model.compile(loss='binary_crossentropy', optimizer=Adam(lr=0.00005), metrics=['accuracy']) model.load_weights('model.h5') load_model('model.h5') predict_me = [] predict_me.append( img_to_array(load_img(fileName, target_size=(224, 224)))) predict_me = np.array(predict_me, dtype=float) result = model.predict(predict_me) > 0.5 result = result.astype(int).sum(axis=1) - 1 #i = image.load_img(fileName, target_size=(224,224)) #i = np.expand_dims(i, axis = 0) #result = model.predict(i) if result == 4: self.setWindowTitle("Proliferative DR") elif result == 3: self.setWindowTitle("Severe") elif result == 2: self.setWindowTitle("Moderate") elif result == 1: self.setWindowTitle("Mild") else: self.setWindowTitle("No DR") def print_(self): dialog = QPrintDialog(self.printer, self) if dialog.exec_(): painter = QPainter(self.printer) rect = painter.viewport() size = self.imageLabel.pixmap().size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(self.imageLabel.pixmap().rect()) painter.drawPixmap(0, 0, self.imageLabel.pixmap()) def zoomIn(self): self.scaleImage(1.25) def zoomOut(self): self.scaleImage(0.8) def normalSize(self): self.imageLabel.adjustSize() self.scaleFactor = 1.0 def fitToWindow(self): fitToWindow = self.fitToWindowAct.isChecked() self.scrollArea.setWidgetResizable(fitToWindow) if not fitToWindow: self.normalSize() self.updateActions() def about(self): QMessageBox.about( self, "About Retinopathy", "<p> <b>paypal.me/retinopathy</b> </p>" "<p>This program evaluated on the quadratic weighted kappa " "with an average over 80. " "Images have five possible ratings, 0,1,2,3,4. " "0 - No DR, 1 - Mild, 2 - Moderate, 3 - Severe, " "4 - Proliferative DR</p>" "<p>Diabetic retinopathy is the leading cause of " "blindness among working aged adults. " "Hopefully this program will improve " "the ability to identify potential patients. " "<p>This piece was made by <b>Vadim Makarenkov</b></p>") def createActions(self): self.openAct = QAction("&Open...", self, shortcut="Ctrl+O", triggered=self.open) self.printAct = QAction("&Print...", self, shortcut="Ctrl+P", enabled=False, triggered=self.print_) self.exitAct = QAction("E&xit", self, shortcut="Ctrl+Q", triggered=self.close) self.zoomInAct = QAction("Zoom &In (25%)", self, shortcut="Ctrl++", enabled=False, triggered=self.zoomIn) self.zoomOutAct = QAction("Zoom &Out (25%)", self, shortcut="Ctrl+-", enabled=False, triggered=self.zoomOut) self.normalSizeAct = QAction("&Normal Size", self, shortcut="Ctrl+S", enabled=False, triggered=self.normalSize) self.fitToWindowAct = QAction("&Fit to Window", self, enabled=False, checkable=True, shortcut="Ctrl+F", triggered=self.fitToWindow) self.aboutAct = QAction("&About", self, triggered=self.about) self.aboutQtAct = QAction("About &Qt", self, triggered=QApplication.instance().aboutQt) def createMenus(self): self.fileMenu = QMenu("&File", self) self.fileMenu.addAction(self.openAct) self.fileMenu.addAction(self.printAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.exitAct) self.viewMenu = QMenu("&View", self) self.viewMenu.addAction(self.zoomInAct) self.viewMenu.addAction(self.zoomOutAct) self.viewMenu.addAction(self.normalSizeAct) self.viewMenu.addSeparator() self.viewMenu.addAction(self.fitToWindowAct) self.helpMenu = QMenu("&Help", self) self.helpMenu.addAction(self.aboutAct) self.helpMenu.addAction(self.aboutQtAct) self.menuBar().addMenu(self.fileMenu) self.menuBar().addMenu(self.viewMenu) self.menuBar().addMenu(self.helpMenu) def updateActions(self): self.zoomInAct.setEnabled(not self.fitToWindowAct.isChecked()) self.zoomOutAct.setEnabled(not self.fitToWindowAct.isChecked()) self.normalSizeAct.setEnabled(not self.fitToWindowAct.isChecked()) def scaleImage(self, factor): self.scaleFactor *= factor self.imageLabel.resize(self.scaleFactor * self.imageLabel.pixmap().size()) self.adjustScrollBar(self.scrollArea.horizontalScrollBar(), factor) self.adjustScrollBar(self.scrollArea.verticalScrollBar(), factor) self.zoomInAct.setEnabled(self.scaleFactor < 3.0) self.zoomOutAct.setEnabled(self.scaleFactor > 0.333) def adjustScrollBar(self, scrollBar, factor): scrollBar.setValue( int(factor * scrollBar.value() + ((factor - 1) * scrollBar.pageStep() / 2)))
class Simple(QMainWindow): x = 'SiO2' y = [ 'Al2O3','MgO', 'FeO', 'CaO', 'Na2O', 'TiO2', 'K2O', 'P2O5'] SR = 'Strike' MR = 'Strike' def __init__(self): super().__init__() self.initUI() def initUI(self): Tas = QPushButton("Tas-1986", self) Tas.move(80, 30) Tas.clicked.connect(self.Tas) TasW = QPushButton("Tas Wilson", self) TasW.move(250, 30) TasW.clicked.connect(self.TasW) TasV = QPushButton("Tas Volcano", self) TasV.move(420, 30) TasV.clicked.connect(self.TasV) TasI = QPushButton("Tas Intrusion", self) TasI.move(590, 30) TasI.clicked.connect(self.TasI) Ree = QPushButton("Ree", self) Ree.move(80, 80) Ree.clicked.connect(self.Ree) Trace1 = QPushButton("Trace Cs->", self) Trace1.move(250, 80) Trace1.clicked.connect(self.Trace1) Trace2 = QPushButton("Trace Rb->", self) Trace2.move(420, 80) Trace2.clicked.connect(self.Trace2) CIPW= QPushButton("CIPW", self) CIPW.move(590, 80) CIPW.clicked.connect(self.CIPW) Ballard = QPushButton("Ballard", self) Ballard.move(590, 130) Ballard.clicked.connect(self.Ballard) MultiBallard = QPushButton("MultiBallard", self) MultiBallard.move(590, 180) MultiBallard.clicked.connect(self.MultiBallard) Qfl = QPushButton("Qfl", self) Qfl.move(250, 130) Qfl.clicked.connect(self.Qfl) Qmflt = QPushButton("Qmflt", self) Qmflt.move(80, 130) Qmflt.clicked.connect(self.Qmflt) QapfP = QPushButton("QapfP", self) QapfP.move(250, 180) QapfP.clicked.connect(self.QapfP) QapfV = QPushButton("QapfV", self) QapfV.move(80, 180) QapfV.clicked.connect(self.QapfV) Pearce = QPushButton("Pearce", self) Pearce.move(80, 360) Pearce.clicked.connect(self.Pearce) Harker = QPushButton("Harker", self) Harker.move(250, 360) Harker.clicked.connect(self.Harker) SingleRose= QPushButton("SingleRose", self) SingleRose.move(420, 360) SingleRose.clicked.connect(self.SingleRose) MultiRose= QPushButton("MultiRose", self) MultiRose.move(590, 360) MultiRose.clicked.connect(self.MultiRose) Wulf = QPushButton("Wulff", self) Wulf.move(420, 410) Wulf.clicked.connect(self.Wulf) Schmidt= QPushButton("Schmidt", self) Schmidt.move(590, 410) Schmidt.clicked.connect(self.Schmidt) self.lbl_hintX = QLabel(self) self.lbl_hintX.move(80, 250) self.lbl_hintX.setText("Input X for Harker:") self.lbl_hintX.adjustSize() self.lbl_hintY = QLabel(self) self.lbl_hintY.move(250, 250) self.lbl_hintY.setText("Input Y for Harker:") self.lbl_hintY.adjustSize() set_X = QLineEdit(self) set_X.move(80, 280) set_X.textChanged[str].connect(self.XChanged) set_Y = QLineEdit(self) set_Y.move(250, 280) set_Y.textChanged[str].connect(self.YChanged) self.lbl_X = QLabel(self) self.lbl_X.move(80, 330) self.lbl_Y = QLabel(self) self.lbl_Y.move(250, 330) self.lbl_SR = QLabel(self) self.lbl_SR.move(420, 330) self.lbl_MR = QLabel(self) self.lbl_MR.move(590, 330) self.lbl_hintSR = QLabel(self) self.lbl_hintSR.move(420, 250) self.lbl_hintSR.setText("Items for SingleRose:") self.lbl_hintSR.adjustSize() self.lbl_hintMR = QLabel(self) self.lbl_hintMR.move(590, 250) self.lbl_hintMR.setText("Item for MultiRose:") self.lbl_hintMR.adjustSize() set_SR = QLineEdit(self) set_SR.move(420, 280) set_SR.textChanged[str].connect(self.SRChanged) set_MR = QLineEdit(self) set_MR.move(590, 280) set_MR.textChanged[str].connect(self.MRChanged) self.lbl_SR = QLabel(self) self.lbl_SR.move(420, 330) self.lbl_MR = QLabel(self) self.lbl_MR.move(590, 330) self.statusBar() self.setGeometry(900, 600, 750, 500) self.setWindowTitle('GeoPython-GUI-Reluctantly') self.show() def XChanged(self, text): self.x='' self.x = str(text) self.lbl_X.setText("X:"+text) self.lbl_X.adjustSize() def YChanged(self, text): self.y = [] self.y = str(text).split() self.lbl_Y.setText("Y:"+text) self.lbl_Y.adjustSize() def SRChanged(self, text): self.SR='' self.SR = str(text) self.lbl_SR.setText("SR:"+text) self.lbl_SR.adjustSize() def MRChanged(self, text): self.MR = [] self.MR = str(text).split() self.lbl_MR.setText("MR:"+text) self.lbl_MR.adjustSize() def buttonClicked(self): sender = self.sender() self.statusBar().showMessage(sender.text() + ' was pressed') def showDialog(self): text, ok = QInputDialog.getText(self, 'Input Dialog', 'Enter Your X:') if ok: self.SetX.setText(str(text)) def Tas(self): a=0 a=gp.Tas_Old() a.read() a = 0 def TasW(self): a=0 a=gp.Tas() a.read() a = 0 def TasV(self): a=0 a=gp.TasV() a.read() a = 0 def TasI(self): a = 0 a=gp.TasI() a.read() a = 0 def Ree(self): a = 0 a = gp.Ree() a.read() a = 0 def CIPW(self): a = 0 a = gp.CIPW() a.read() a = 0 def Trace1(self): a = 0 a=gp.Trace() a.read() a = 0 def Trace2(self): a=0 a=gp.Trace2() a.read() a = 0 def Qfl(self): a=0 a=gp.Qfl() a.read() a=0 def Qmflt(self): a=0 a =gp.Qmflt() a.read() a=0 def QapfP(self): a=0 gp.QapfP().read() a=0 def QapfV(self): a=0 a =gp.QapfV() a.read() a=0 def Wulf(self): a=0 a =gp.Polar() a.wulf() a=0 def Schmidt(self): a=0 a =gp.Polar() a.schmidt() a=0 def SingleRose(self): a=0 a =gp.Polar() a.singlerose(Name=self.SR.split()) a=0 def MultiRose(self): a=0 a =gp.Polar() a.multirose(Name=self.MR.split()[0]) a=0 def Pearce(self): a=0 a =gp.Pearce() a.read() a=0 def Harker(self): print(self.x,"\t",self.y) a=0 a =gp.Harker(x=self.x,y=self.y) a.read() a=0 def Ballard(self): a=0 a = gp.Ballard() a.read() a=0 def MultiBallard(self): b=0 b=gp.MultiBallard() b.read() b=0
class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): # checkbox cb = QCheckBox('Show title', self) cb.move(20, 160) cb.toggle() cb.stateChanged.connect(self.changeTitle) # toggle button self.col = QColor(0, 0, 0) redb = QPushButton('Red', self) redb.setCheckable(True) redb.move(10, 10) redb.clicked[bool].connect(self.setColor) redb = QPushButton('Green', self) redb.setCheckable(True) redb.move(10, 60) redb.clicked[bool].connect(self.setColor) blueb = QPushButton('Blue', self) blueb.setCheckable(True) blueb.move(10, 110) blueb.clicked[bool].connect(self.setColor) self.square = QFrame(self) self.square.setGeometry(150, 20, 100, 100) self.square.setStyleSheet("QWidget { background-color: %s }" % self.col.name()) # slider sld = QSlider(Qt.Horizontal, self) sld.setFocusPolicy(Qt.NoFocus) sld.setGeometry(30, 210, 100, 30) sld.valueChanged[int].connect(self.changeValue) # pixmap self.label = QLabel(self) self.label.setPixmap(QPixmap('web.png')) self.label.setGeometry(160, 210, 80, 30) # process bar self.pbar = QProgressBar(self) self.pbar.setGeometry(30, 260, 200, 25) self.btn = QPushButton('Start', self) self.btn.move(40, 310) self.btn.clicked.connect(self.doAction) self.timer = QBasicTimer() self.step = 0 # calendar cal = QCalendarWidget(self) cal.setGridVisible(True) cal.move(300, 10) cal.clicked[QDate].connect(self.showDate) self.lbl = QLabel(self) date = cal.selectedDate() self.lbl.setText(date.toString()) self.lbl.move(300, 260) # line edit self.lbl2 = QLabel(self) qle = QLineEdit(self) qle.move(300, 310) self.lbl2.move(480, 310) qle.textChanged[str].connect(self.onChanged) self.setGeometry(300, 300, 640, 480) self.setWindowTitle('QCheckBox') self.show() def changeTitle(self, state): if state == Qt.Checked: self.setWindowTitle('QCheckBox') else: self.setWindowTitle('') def setColor(self, pressed): source = self.sender() if pressed: val = 255 else: val = 0 if source.text() == "Red": self.col.setRed(val) elif source.text() == "Green": self.col.setGreen(val) else: self.col.setBlue(val) self.square.setStyleSheet("QFrame { background-color: %s }" % self.col.name()) def changeValue(self, value): if value == 0: self.label.setPixmap(QPixmap('web.png')) elif value > 0 and value <= 30: self.label.setPixmap(QPixmap('web.png')) elif value > 30 and value < 80: self.label.setPixmap(QPixmap('web.png')) else: self.label.setPixmap(QPixmap('web.png')) def timerEvent(self, e): if self.step >= 100: self.timer.stop() self.btn.setText('Finished') return self.step = self.step + 1 self.pbar.setValue(self.step) def doAction(self): if self.timer.isActive(): self.timer.stop() self.btn.setText('Start') else: self.timer.start(100, self) self.btn.setText('Stop') def showDate(self, date): self.lbl.setText(date.toString()) def onChanged(self, text): self.lbl2.setText(text) self.lbl2.adjustSize()
class Example(QWidget): def __init__(self): super().__init__() self.ventana() def ventana(self): #Planteamiento de etiquetas self.inp= QLineEdit("Numero de datos", self) self.inp.move(5,5) self.x= QLineEdit(self) self.x.move(5,50) self.y= QLineEdit(self) self.y.move(160,50) lbl= QLabel("x", self) lbl.move(5, 30) lbl2= QLabel("y", self) lbl2.move(160, 30) self.lbl3= QLabel(self) self.lbl3.move(5,75) self.inp2=QLineEdit("Conocer X en",self) self.inp2.move(5,100) self.lbl4= QLabel("y=...", self) self.lbl4.move(160,100) self.com= QComboBox(self) self.com.move(160,5) but= QPushButton("Calcular", self) but.move(5,130) #Eventos self.com.activated[str].connect(self.onAc) self.inp.textChanged[str].connect(self.combo) self.x.textChanged[str].connect(self.lx) self.y.textChanged[str].connect(self.ly) self.inp.selectionChanged.connect(self.bor) self.x.selectionChanged.connect(self.bor2) self.y.selectionChanged.connect(self.bor3) self.inp2.selectionChanged.connect(self.bor4) but.clicked.connect(self.boton) #Ventana self.setGeometry(300, 300, 350, 160) self.setWindowTitle('Regresion Lineal') self.show() #Metodos de los eventos def boton(self): sp=0 ss=0 ym= 0 xm= 0 b1=0 b0=0 te= int(self.inp.text()) for c in range(te): ym+= yl[c] xm+= xl[c] c=0 ym/=te xm/=te for c in range(te): sp+= (xl[c]-xm)*(yl[c]-ym) ss+= (xl[c]-xm)**2 b1= sp/ss b0= ym-(b1*xm) if self.inp2.text() == '': self.inp2.setText("0") cp= float(self.inp2.text()) r= b0+(b1*cp) self.lbl4.setText("y="+str(r)) self.lbl4.adjustSize() self.lbl3.setText("y="+str(b0)+"+("+str(b1)+"x)") self.lbl3.adjustSize() def bor(self): self.inp.clear() def bor2(self): self.x.clear() def bor3(self): self.y.clear() def bor4(self): self.inp2.clear() def combo(self, text): self.com.clear() if text =='': text='0' for c in range(int(text)): self.com.addItem(str(c+1)) if len(xl)<= c: xl.append(0) yl.append(0) def lx(self, text): if text == "": text= "0" xl[(self.com.currentIndex())]= float(text) def ly(self, text): if text == "": text= "0" yl[(self.com.currentIndex())]= float(text) def onAc(self, text): if self.x.text()== " ": xl[int(text)-1]= 0 if self.y.text()== " ": yl[int(text)-1]= 0 self.x.setText(str(xl[int(text)-1])) self.y.setText(str(yl[int(text)-1]))
def welcomeWindow(self): # centralWidget = QWidget(self) self.defaultWindow('Home Page') # self.setCentralWidget(centralWidget) #gridLayout = QGridLayout(self) #centralWidget.setLayout(gridLayout) #font_db = QFontDatabase() #font_id = font_db.addApplicationFont("Fonts\Pacifico.ttf") #families = font_db.applicationFontFamilies(font_id) cursor.execute("SELECT * FROM user_info") table = cursor.fetchall() L1 = QLabel("Welcome " + table[0][0], self) L2 = QLabel("Review Information", self) L3 = QLabel("First Name : " + table[0][0], self) L4 = QLabel("Last Name :" + table[0][1], self) L5 = QLabel("Age : " + str(table[0][2]), self) L6 = QLabel("Weight : "+ str(table[0][3]), self) L7 = QLabel("Height : " + str(table[0][4]), self) L8 = QLabel("Calories Intake per day: " + str(table[0][5]), self) L1.setStyleSheet('font-size: 25pt ') L2.setStyleSheet('font-size: 20pt ') L3.setStyleSheet('font-size: 18pt ') L4.setStyleSheet('font-size: 18pt ') L5.setStyleSheet('font-size: 18pt ') L6.setStyleSheet('font-size: 18pt ') L7.setStyleSheet('font-size: 18pt ') L8.setStyleSheet('font-size: 18pt ') # h3Font = QFont(families[0],30, QFont.Bold) #h2Font = QFont(families[0],16, QFont.DemiBold) #h1Font = QFont(families[0],12) # L1.setFont(h3Font) L1.move(350,50) #L2.setFont(h2Font) L2.move(50, 220) # L3.setFont(h1Font) L3.move(70,300) #L4.setFont(h1Font) L4.move(70,380) # L5.setFont(h1Font) L5.move(70,460) # L6.setFont(h1Font) L6.move(70,520) # L7.setFont(h1Font) L7.move(70,600) # L8.setFont(h1Font) L8.move(70 ,680) L1.adjustSize() L2.adjustSize() L3.adjustSize() L4.adjustSize() L5.adjustSize() L6.adjustSize() L7.adjustSize() L8.adjustSize() qtRectangle = self.frameGeometry() centerPoint = QDesktopWidget().availableGeometry().center() qtRectangle.moveCenter(centerPoint) self.move(qtRectangle.topLeft()) qtRectangle.moveCenter(centerPoint) self.move(qtRectangle.topLeft()) buttonM = QPushButton("Modify",self) buttonM.setStyleSheet('QPushButton {background-color: #A3C1DA; color: blue;}') buttonM.resize(100,50) buttonM.move(100,800) buttonM.clicked.connect(self.modifyWindow) buttonS = QPushButton("Table",self) buttonS.setStyleSheet('QPushButton {background-color: #A3C1DA; color: blue;}') buttonS.resize(100,50) buttonS.move(700,800) buttonS.clicked.connect(self.tableWindow)
class MainWindow(QMainWindow): def __init__(self): super().__init__() self._suggester = suggester.Suggester() self._pickedfiles = [] self._targetmidi = [] self.inputlistview = None self.suggestionlistview = None self.target_lbl = None self.initUI() def initUI(self): targetButton = QPushButton('Select Target', self) targetButton.setToolTip('Select midi you want suggestions for') targetButton.resize(targetButton.sizeHint()) targetButton.clicked.connect(self.picktargetmidi) self.inputlistview = QListWidget() self.inputlistview.itemPressed.connect(self.showmidi) inputlistview_lbl = QLabel(self) inputlistview_lbl.setText("Input MIDIs") inputlistview_lbl.adjustSize() suggestionlistview_lbl = QLabel(self) suggestionlistview_lbl.setText("Suggested segments") suggestionlistview_lbl.adjustSize() self.target_lbl = QLabel(self) self.target_lbl.setText("Please select target midi") self.target_lbl.adjustSize() self.suggestionlistview = QListWidget() suggestButton = QPushButton("Suggest", self) suggestButton.setToolTip('Suggest a continuation to target midi') suggestButton.clicked.connect(self.suggestmidi) saveButton = QPushButton("Save Suggestions", self) importAction = QAction(self.tr('Add MIDI file(s)'), self) importAction.setShortcut('Ctrl+O') importAction.setStatusTip('Add MIDI files to pool') importAction.triggered.connect(self.pickfiles) hbox = QHBoxLayout() hbox.addStretch(1) hbox.addWidget(self.target_lbl) hbox.addWidget(targetButton) hbox.addWidget(suggestButton) hbox.addWidget(saveButton) vbox = QVBoxLayout() vbox.addStretch(1) vbox.addWidget(inputlistview_lbl) vbox.addWidget(self.inputlistview) vbox.addLayout(hbox) vbox.addWidget(suggestionlistview_lbl) vbox.addWidget(self.suggestionlistview) cwidget = QWidget() cwidget.setLayout(vbox) self.setCentralWidget(cwidget) self.statusBar().showMessage('Ready') self.statusBar() menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(importAction) self.center() self.setGeometry(150,20,100,100) self.setWindowTitle('Gnotestic') self.show() def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def pickfiles(self, point): dialog_result = QFileDialog.getOpenFileNames(self, self.tr("Import Midi"), "", self.tr("Midi Files (*.mid *.midi)")) self._pickedfiles.extend(dialog_result[0]) self.updatemidilist(dialog_result[0]) def picktargetmidi(self, point): dialog_result = QFileDialog.getOpenFileName(self, self.tr("Select Target Midi"), "", self.tr("Midi Files (*.mid *.midi)")) self._targetmidi = dialog_result[0] def updatemidilist(self, items): for item in items: witem = QListWidgetItem(item) self.inputlistview.addItem(witem) def showmidi(self, item): path = item.text() ms = converter.parse(path) ms.plot('pianoroll') def suggestmidi(self, point): #add midis to suggester if self._targetmidi and self.inputlistview.count(): self._suggester.set_target_piece(self._targetmidi) for i in range(self.inputlistview.count()): self._suggester.add_midi(self.inputlistview.item(i).text()) #update suggestion list self.suggestionlistview.clear() for suggestion in self._suggester.get_suggestions(): self.suggestionlistview.addItem(QListWidgetItem(repr(suggestion)))
class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.lbl1 = QLabel("RGB: ", self) #setting label text for RGB self.lbl2 = QLabel("Hex: ", self) #setting label text for HEX self.my_btn = QPushButton("Show Color!", self) #setting button for new window self.my_btn.clicked.connect(self.on_click, ) combo = QComboBox(self) #init combo box combo.addItem("Emerald") #adding color to box combo.addItem("Diamond") #^^ combo.addItem("Copper") #^^ combo.addItem("Platinum") #^^ combo.addItem("Gold") #^^ combo.move(100, 50) #setting position of combo box self.lbl1.move( 30, 150 ) #Setting label 1 farther to the left to create room for the text self.lbl2.move( 170, 150 ) #Setting label 2 farther to the right to give text more room for other text (Gold) combo.activated[str].connect(self.onActivated) self.setGeometry(300, 300, 300, 200) #window dimensions self.setWindowTitle('RGB/HEX') self.show() def onActivated(self, text): if (text == "Emerald"): #check for color then set values accordlingly self.lbl1.setText("RGB: (31,78,47)") self.lbl1.adjustSize() self.lbl2.setText("HEX: #50c878") self.lbl2.adjustSize() if (text == "Diamond"): #check for color then set values accordlingly self.lbl1.setText("RGB: (185,242,255)") self.lbl1.adjustSize() self.lbl2.setText("HEX: #B9F2FF") self.lbl2.adjustSize() if (text == "Copper"): #check for color then set values accordlingly self.lbl1.setText("RGB: (72,45,20)") self.lbl1.adjustSize() self.lbl2.setText("HEX: #b87333") self.lbl2.adjustSize() if (text == "Platinum"): #check for color then set values accordlingly self.lbl1.setText("RGB: (90,89,89)") self.lbl1.adjustSize() self.lbl2.setText("HEX: #e5e4e2") self.lbl2.adjustSize() if (text == "Gold"): #check for color then set values accordlingly self.lbl1.setText("RGB: (255,215,0)") self.lbl1.adjustSize() self.lbl2.setText("HEX: #FFD700") self.lbl2.adjustSize()
class MapWindow(QWidget): ''' Main class of the game GUI. ''' def __init__(self): super().__init__() self.setAcceptDrops(True) self.game = Game(4) # Make game with 4 players self.sig = Signals() endTurnButton = QPushButton("&EndTurn", self) endTurnButton.clicked.connect(self.endTurn) endTurnButton.move(1260, 720) turnLcd = QLCDNumber(3, self) turnLcd.move(90, 715) turnLcd.setSegmentStyle(QLCDNumber.Filled) turnLcd.resize(60, 40) turnTxt = QLabel("Turn:", self) turnFont = QFont() turnFont.setPointSize(20) turnTxt.setFont(turnFont) turnTxt.move(20, 720) self.sig.turnChanged.connect(turnLcd.display) self.sig.turnChanged.emit(self.game.turn) quitB = QPushButton("&Quit", self) quitB.clicked.connect(self.quit) quitB.move(1150, 720) self.showPlayerInfo() self.coords = [] self.setWindowTitle("Territory War") n = self.game.map.dim self.makeMap(1100 // n, 600 // n, n) self.setWindowState(Qt.WindowFullScreen) self.setFixedSize(self.size()) self.showArmies() self.addDiplomacyLabels() thread = threading.Thread(target=self.game.start, args=(0, )) thread.start() def endTurn(self): ''' Method to end the current player's turn and refresh all the interface to show the next active player's info. ''' self.game.player.end_turn.release() time.sleep(1) self.sig.turnChanged.emit(self.game.turn) self.player.setText(self.game.player.name) color = QColor(*self.game.player.color).name() self.player.adjustSize() self.player.setStyleSheet("QWidget { color: %s }" % color) self.sig.goldChanged.emit(self.game.player.gold) self.sig.incomeChanged.emit(self.game.player.income()) maint = self.game.player.get_armies_maint() self.sig.maintChanged.emit(maint[0] + maint[1]) for row in self.coords: for ter in row: ter.update() self.updateButtons() self.raisePlayerArmies(self.game.player) self.showOffers() def makeMap(self, width, height, n): ''' Generates the graphical map, from the game's map. Sets events and connects signals for the territories. ''' for i in range(n): self.coords.append([]) for j in range(n): ter_square = TerritorySquare(self, self.game.map.map[i][j]) self.coords[i].append(ter_square) square = self.coords[i][j] square.mouseReleaseEvent = self.showTerritoryDialog square.incomeChanged.emit(square.ter.get_income()) square.marketUpgr.emit(square.ter.buildings.market_lvl) square.fortUpgr.emit(square.ter.buildings.fort_lvl) x = 110 + i * (width + 1) y = 60 + j * (height + 1) square.setGeometry(x, y, width, height) if square.ter.owner: color = QColor(*square.ter.owner.color) else: color = QColor(127, 127, 127) bgcolor = "QWidget { background-color: %s }" square.setStyleSheet(bgcolor % color.name()) square.calcCenter() def showTerritoryDialog(self, event): territory_dialog = TerritoryDialog(self, event) territory_dialog.setWindowTitle("Territory") territory_dialog.setWindowModality(Qt.ApplicationModal) territory_dialog.setFixedSize(280, 240) territory_dialog.exec_() def showPlayerInfo(self): ''' Displays player name label. ''' nameLbl = QLabel('Player Name:', self) nameLbl.move(10, 10) font = QFont() font.setPointSize(17) nameLbl.setFont(font) self.addGoldInfo(font) self.addPlayerInfo(font) self.addIncomeInfo(font) self.addMaintInfo(font) def addGoldInfo(self, font): ''' Adds gold LCDNumber and connects it with the correct signal. ''' goldLbl = QLabel('Gold:', self) goldLbl.move(300, 10) goldLbl.setFont(font) goldLcd = QLCDNumber(4, self) goldLcd.move(360, 0) goldLcd.setFrameShape(QFrame.NoFrame) goldLcd.resize(65, 40) self.sig.goldChanged.connect(goldLcd.display) self.sig.goldChanged.emit(self.game.player.gold) def addPlayerInfo(self, font): ''' Shows current player's name and adds event for changing player's name. ''' self.player = QLabel(self.game.player.name, self) color = QColor(*self.game.player.color).name() self.player.setGeometry(150, 10, 40, 30) self.player.setFont(QFont(font.family(), 16, 200, True)) self.player.setStyleSheet("QWidget { color: %s }" % color) self.player.adjustSize() self.player.mouseReleaseEvent = self.changePlayerName def addIncomeInfo(self, font): ''' Adds the income LCDNumber and connects it with the correct signals. ''' incomeLbl = QLabel("Income:", self) incomeLbl.setFont(font) incomeLbl.move(460, 10) incomeLcd = QLCDNumber(3, self) incomeLcd.move(530, 0) incomeLcd.setFrameShape(QFrame.NoFrame) incomeLcd.resize(60, 40) self.sig.incomeChanged.connect(incomeLcd.display) self.sig.incomeChanged.emit(self.game.player.income()) def addMaintInfo(self, font): ''' Adds maintenance QLCDNumber and connects it with the correct signals. ''' maintLbl = QLabel("Total maintenance:", self) maintLbl.move(620, 10) maintLbl.setFont(font) maintLcd = QLCDNumber(3, self) maintLcd.move(840, 7) maintLcd.setFrameShape(QFrame.NoFrame) maintLcd.resize(50, 30) self.sig.maintChanged.connect(maintLcd.display) maint = self.game.player.get_armies_maint() self.sig.maintChanged.emit(maint[0] + maint[1]) def addDiplomacyLabels(self): ''' Displays diplomatic labels for every player. ''' y = 100 font = QFont() font.setPointSize(17) self.diploLbls = [] for player in self.game.players: lbl = DiploLabel(player.name, self) lbl.move(1230, y) color = player.color lbl.setStyleSheet("QWidget { color: %s }" % QColor(*color).name()) lbl.setFont(QFont(font.family(), 16, 200, True)) self.diploLbls.append(lbl) y = y + 50 diplomacy = QLabel("Diplomacy", self) diplomacy.move(1230, 50) diplomacy.setFont(QFont(font.family(), 16, 200, True)) def updateDiploLabels(self): ''' Updates diplomatic label's texts when any player's name is changed. ''' for i in range(len(self.game.players)): self.diploLbls[i].setText(self.game.players[i].name) def changePlayerName(self, event): ''' Method that calls input dialog to change player's name. ''' input = QInputDialog(self) input.setLabelText("Name") input.setWindowTitle("Change name") if input.exec_() == 1: newName = input.textValue() self.game.player.name = newName self.player.setText(newName) self.updateDiploLabels() def showArmies(self): ''' Initially adds players' armies in the GUI. ''' self.armies = [] for player in self.game.players: for army in player.armies: x = army.pos_x y = army.pos_y center = self.coords[x][y].center self.armies.append(ArmySquare(self, army, center)) self.addArmyButtons() def raisePlayerArmies(self, player): ''' Raises player's armies to the top of the map layer. ''' for army in self.armies: if army.army.owner is player: army.raise_() if army.army.killed(): army.close() def addArmyButtons(self): ''' Adds buttons for upgrading of the player's units and connects these buttons to the responsible methods. ''' infPrice = self.game.player.inf_price * 2 self.infB = QPushButton("Upgrade infantry: {}".format(infPrice), self) self.infB.move(0, 100) self.infB.setEnabled(self.game.player.can_upgr_inf()) self.infB.clicked.connect(self.upgrInf) cavPrice = self.game.player.cav_price * 2 self.cavB = QPushButton("Upgrade cavlary: {}".format(cavPrice), self) self.cavB.move(0, 130) self.cavB.setEnabled(self.game.player.can_upgr_cav()) self.cavB.clicked.connect(self.upgrCav) def upgrCav(self, event): ''' Upgrades player's cavlary units. ''' player = self.game.player player.upgr_cav() self.updateButtons() self.sig.goldChanged.emit(player.gold) def upgrInf(self, event): ''' Upgrades player's infantry units. ''' player = self.game.player player.upgr_inf() self.updateButtons() self.sig.goldChanged.emit(player.gold) def updateButtons(self): ''' Updates unit upgrade buttons with the new upgrade prices. ''' player = self.game.player self.infB.setText("Upgrade infantry: {}".format(player.inf_price * 2)) self.cavB.setText("Upgrade cavlary: {}".format(player.cav_price * 2)) self.cavB.setEnabled(player.can_upgr_cav()) self.infB.setEnabled(player.can_upgr_inf()) def showOffers(self): ''' Displays dialogs with the pending offers of the current player. ''' for offer in self.game.player.offers: offerDialog = OfferDialog(offer) if offerDialog.exec_() == 1: offer.accept() self.sig.goldChanged.emit(self.game.player.gold) self.game.player.offers = [] def quit(self): self.game.turn = -1 for player in self.game.players: player.end_turn.release() time.sleep(1) self.close()
class InputPage(Page): '''Page for user to enter all their expenses in table''' def __init__(self): #Constructor super().__init__() self.table = QTableWidget(self) self.currentRowCount = 0 self.inputWindow() self.printTable() self.addButton() self.clearButton() self.saveButton() self.backButton() self.show() def inputWindow(self): #Display the input page self.defaultWindow("Input Page") self.label = QLabel("Input Your Nutritional Details", self) self.label.setStyleSheet("font-size: 20pt; font-weight: bold") self.label.setFixedWidth(1000) self.label.move(0,0) self.label.adjustSize() self.label.setAlignment(Qt.AlignCenter) def printTable(self): #Display the user input table self.table.setStyleSheet("background-color: white; border: 1px solid black") self.table.setRowCount(1) self.table.setColumnCount(6) self.table.resize(775,800) self.table.move(100,50) font = QFont() font.setBold(True) font.setPointSize(11) columns = ["Description","Amount (g)","Calories","Carbs (g)","Protein (g)","Fat (g)"] #Set up each of the table's columns for count, column in enumerate(columns): item = QTableWidgetItem() item.setText(column) item.setTextAlignment(Qt.AlignCenter) item.setFlags(Qt.ItemIsEnabled) self.table.setItem(0,count, item) self.table.item(0,count).setFont(font) cursor.execute("SELECT * FROM food_info") foods = cursor.fetchall() for x,food in enumerate(foods,1): self.addRow(self.table) for y, column in enumerate(columns): item = QTableWidgetItem() item.setText(str(food[y])) self.table.setItem(x,y,item) def backButton(self): #Display the add a row button self.pushButton = QPushButton("Back", self) self.pushButton.move(0,0) self.pushButton.setStyleSheet("background-color: white; font-size: 24px") self.pushButton.resize(78,50) self.pushButton.setToolTip("<h4>Click to go back mofo</h4>") self.pushButton.clicked.connect(self.backWindow) def backWindow(self): self.w = WelcomePage() self.w.show() self.hide() def addButton(self): #Display the add a row button self.pushButton = QPushButton("+", self) self.pushButton.move(900,50) self.pushButton.setStyleSheet("background-color: white; font-size: 24px") self.pushButton.resize(78,50) self.pushButton.setToolTip("<h4>Add an item</h4>") self.pushButton.clicked.connect(lambda: self.addRow(self.table)) def clearButton(self): #Display the stats button self.pushButton = QPushButton("Clear all", self) self.pushButton.move(900,800) self.pushButton.setStyleSheet("background-color: white; font-size: 16px") self.pushButton.setToolTip("<h4>Clear all details</h4>") self.pushButton.clicked.connect(lambda: self.clear()) self.pushButton.resize(78,50) def addRow(self,table): #Add a row to the table self.currentRowCount += 1 self.table.insertRow(self.currentRowCount) def saveButton(self): #Display the stats button self.pushButton = QPushButton("Save", self) self.pushButton.move(440,850) self.pushButton.setStyleSheet("background-color: white; font-size: 16px") self.pushButton.setToolTip("<h4>Save your details</h4>") self.pushButton.clicked.connect(lambda: self.save(self.table)) self.pushButton.resize(125,50) def save(self,table): #Save with valid input clear_food_table(cursor) for count in range(1,self.table.rowCount()): #Check for valid amount input try: descr = self.table.item(count,0).text() except: self.errorMessage("Invalid Description") return None try: amount = float(self.table.item(count,1).text()) except: self.errorMessage("Invalid Amount Input") return None try: cal = int(self.table.item(count,2).text()) except: self.errorMessage("Invalid Calories Input") return None try: carbs = float(self.table.item(count,3).text()) except: self.errorMessage("Invalid Carbohydrates Input") return None try: protein = float(self.table.item(count,4).text()) except: self.errorMessage("Invalid Protein Input") return None try: fat = float(self.table.item(count,5).text()) except: self.errorMessage("Invalid Fat Input") return None food = (descr,amount,cal,carbs,protein,fat) add_food_info(cursor,food) def clear(self): clear_food_table(cursor) self.currentRowCount = 0 self.printTable()
class Window(QMainWindow, Ui_window): renderRequested = QtCore.pyqtSignal(int, float) loadFileRequested = QtCore.pyqtSignal(str, str) findTextRequested = QtCore.pyqtSignal(str, int, bool) def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.setupUi(self) self.dockSearch.hide() self.dockWidget.hide() self.dockWidget.setMinimumWidth(310) self.findTextEdit.setFocusPolicy(QtCore.Qt.StrongFocus) self.treeView.setAlternatingRowColors(True) self.treeView.clicked.connect(self.onOutlineClick) # resizing pages requires some time to take effect self.resize_page_timer = QtCore.QTimer(self) self.resize_page_timer.setSingleShot(True) self.resize_page_timer.timeout.connect(self.onWindowResize) # Add shortcut actions self.gotoPageAction = QAction(QIcon(":/goto.png"), "GoTo Page", self) self.gotoPageAction.triggered.connect(self.gotoPage) self.copyTextAction = QAction(QIcon(":/copy.png"), "Copy Text", self) self.copyTextAction.setCheckable(True) self.copyTextAction.triggered.connect(self.toggleCopyText) self.findTextAction = QAction(QIcon(":/search.png"), "Find Text", self) self.findTextAction.setShortcut('Ctrl+F') self.findTextAction.triggered.connect(self.dockSearch.show) # connect menu actions signals self.openFileAction.triggered.connect(self.openFile) self.lockUnlockAction.triggered.connect(self.lockUnlock) self.printAction.triggered.connect(self.printFile) self.quitAction.triggered.connect(self.close) self.toPSAction.triggered.connect(self.exportToPS) self.pageToImageAction.triggered.connect(self.exportPageToImage) self.docInfoAction.triggered.connect(self.docInfo) self.zoominAction.triggered.connect(self.zoomIn) self.zoomoutAction.triggered.connect(self.zoomOut) self.undoJumpAction.triggered.connect(self.undoJump) self.prevPageAction.triggered.connect(self.goPrevPage) self.nextPageAction.triggered.connect(self.goNextPage) self.firstPageAction.triggered.connect(self.goFirstPage) self.lastPageAction.triggered.connect(self.goLastPage) # Create widgets for menubar / toolbar self.gotoPageEdit = QLineEdit(self) self.gotoPageEdit.setPlaceholderText("Jump to page...") self.gotoPageEdit.setMaximumWidth(120) self.gotoPageEdit.returnPressed.connect(self.gotoPage) self.gotoPageValidator = QIntValidator(1, 1, self.gotoPageEdit) self.gotoPageEdit.setValidator(self.gotoPageValidator) self.pageNoLabel = QLabel(self) self.pageNoLabel.setFrameShape(QFrame.StyledPanel) spacer = QWidget(self) spacer.setSizePolicy(1 | 2 | 4, 1 | 4) self.zoomLevelCombo = QComboBox(self) self.zoomLevelCombo.addItems([ "Fixed Width", "75%", "90%", "100%", "110%", "121%", "133%", "146%", "175%", "200%" ]) self.zoomLevelCombo.activated.connect(self.setZoom) self.zoom_levels = [0, 75, 90, 100, 110, 121, 133, 146, 175, 200] # Add toolbar actions self.toolBar.addAction(self.openFileAction) self.toolBar.addAction(self.printAction) self.toolBar.addSeparator() self.toolBar.addAction(self.docInfoAction) self.toolBar.addSeparator() self.toolBar.addAction(self.zoomoutAction) self.toolBar.addWidget(self.zoomLevelCombo) self.toolBar.addAction(self.zoominAction) self.toolBar.addSeparator() self.toolBar.addAction(self.firstPageAction) self.toolBar.addAction(self.prevPageAction) self.toolBar.addWidget(self.pageNoLabel) self.toolBar.addAction(self.nextPageAction) self.toolBar.addAction(self.lastPageAction) self.toolBar.addAction(self.undoJumpAction) self.toolBar.addWidget(self.gotoPageEdit) self.toolBar.addAction(self.gotoPageAction) self.toolBar.addSeparator() self.toolBar.addAction(self.copyTextAction) self.toolBar.addAction(self.findTextAction) #self.toolBar.addAction(self.saveUnlockedAction) self.toolBar.addWidget(spacer) self.toolBar.addSeparator() self.toolBar.addAction(self.quitAction) # Add widgets self.statusbar = QLabel(self) self.statusbar.setStyleSheet( "QLabel { font-size: 12px; border-radius: 2px; padding: 2px; background: palette(highlight); color: palette(highlighted-text); }" ) self.statusbar.setMaximumHeight(16) self.statusbar.hide() # Impoort settings desktop = QApplication.desktop() self.settings = QtCore.QSettings("gospel-pdf", "main", self) self.recent_files = self.settings.value("RecentFiles", []) self.history_filenames = self.settings.value("HistoryFileNameList", []) self.history_page_no = self.settings.value("HistoryPageNoList", []) self.offset_x = int(self.settings.value("OffsetX", 4)) self.offset_y = int(self.settings.value("OffsetY", 26)) self.available_area = [ desktop.availableGeometry().width(), desktop.availableGeometry().height() ] self.zoomLevelCombo.setCurrentIndex( int(self.settings.value("ZoomLevel", 2))) # Connect Signals self.scrollArea.verticalScrollBar().valueChanged.connect( self.onMouseScroll) self.scrollArea.verticalScrollBar().sliderReleased.connect( self.onSliderRelease) self.findTextEdit.returnPressed.connect(self.findNext) self.findNextButton.clicked.connect(self.findNext) self.findBackButton.clicked.connect(self.findBack) self.findCloseButton.clicked.connect(self.dockSearch.hide) self.dockSearch.visibilityChanged.connect(self.toggleFindMode) # Create separate thread and move renderer to it self.thread1 = QtCore.QThread(self) self.renderer1 = Renderer(0) self.renderer1.moveToThread( self.thread1) # this must be moved before connecting signals self.renderRequested.connect(self.renderer1.render) self.loadFileRequested.connect(self.renderer1.loadDocument) self.findTextRequested.connect(self.renderer1.findText) self.renderer1.rendered.connect(self.setRenderedImage) self.renderer1.textFound.connect(self.onTextFound) self.thread1.start() self.thread2 = QtCore.QThread(self) self.renderer2 = Renderer(1) self.renderer2.moveToThread(self.thread2) self.renderRequested.connect(self.renderer2.render) self.loadFileRequested.connect(self.renderer2.loadDocument) self.renderer2.rendered.connect(self.setRenderedImage) self.thread2.start() # Initialize Variables self.doc = None self.filename = '' self.passwd = '' self.pages = [] self.jumped_from = None self.max_preload = 1 self.recent_files_actions = [] self.addRecentFiles() # Show Window width = int(self.settings.value("WindowWidth", 1040)) height = int(self.settings.value("WindowHeight", 717)) self.resize(width, height) self.show() def addRecentFiles(self): self.recent_files_actions[:] = [] # pythonic way to clear list self.menuRecentFiles.clear() for each in self.recent_files: name = elideMiddle(os.path.basename(each), 60) action = self.menuRecentFiles.addAction(name, self.openRecentFile) self.recent_files_actions.append(action) self.menuRecentFiles.addSeparator() self.menuRecentFiles.addAction(QIcon(':/edit-clear.png'), 'Clear Recents', self.clearRecents) def openRecentFile(self): action = self.sender() index = self.recent_files_actions.index(action) self.loadPDFfile(self.recent_files[index]) def clearRecents(self): self.recent_files_actions[:] = [] self.menuRecentFiles.clear() self.recent_files[:] = [] def removeOldDoc(self): if not self.doc: return # Save current page number self.saveFileData() # Remove old document for i in range(len(self.pages)): self.verticalLayout.removeWidget(self.pages[-1]) for i in range(len(self.pages)): self.pages.pop().deleteLater() self.frame.deleteLater() self.jumped_from = None self.addRecentFiles() def loadPDFfile(self, filename): """ Loads pdf document in all threads """ filename = os.path.expanduser(filename) doc = Poppler.Document.load(filename) if not doc: return password = '' if doc.isLocked(): password = QInputDialog.getText(self, 'This PDF is locked', 'Enter Password :'******'': if self.doc == None: sys.exit(1) #exif if first document else: return locked = doc.unlock(password.encode(), password.encode()) if locked: return QMessageBox.critical(self, "Failed !", "Incorrect Password") self.passwd = password self.lockUnlockAction.setText("Save Unlocked") else: self.lockUnlockAction.setText("Encrypt PDF") self.removeOldDoc() doc.setRenderHint(Poppler.Document.TextAntialiasing | Poppler.Document.TextHinting | Poppler.Document.Antialiasing | Poppler.Document.ThinLineSolid) self.doc = doc self.filename = filename self.pages_count = self.doc.numPages() self.current_page = 1 self.rendered_pages = [] self.getOutlines(self.doc) # Load Document in other threads self.loadFileRequested.emit(self.filename, password) if collapseUser(self.filename) in self.history_filenames: self.current_page = int( self.history_page_no[self.history_filenames.index( collapseUser(self.filename))]) self.current_page = min(self.current_page, self.pages_count) self.scroll_render_lock = False # Add widgets self.frame = Frame(self.scrollAreaWidgetContents, self.scrollArea) self.verticalLayout = QVBoxLayout(self.frame) self.horizontalLayout_2.addWidget(self.frame) self.scrollArea.verticalScrollBar().setValue(0) self.frame.jumpToRequested.connect(self.jumpToPage) self.frame.copyTextRequested.connect(self.copyText) self.frame.showStatusRequested.connect(self.showStatus) # Render 4 pages, (Preload 3 pages) self.max_preload = min(4, self.pages_count) # Add pages for i in range(self.pages_count): page = PageWidget(i + 1, self.frame) self.verticalLayout.addWidget(page, 0, QtCore.Qt.AlignCenter) self.pages.append(page) self.resizePages() self.pageNoLabel.setText('<b>%i/%i</b>' % (self.current_page, self.pages_count)) self.gotoPageValidator.setTop(self.pages_count) self.setWindowTitle( os.path.basename(self.filename) + " - Gospel PDF " + __version__) if self.current_page != 1: QtCore.QTimer.singleShot(150 + self.pages_count // 3, self.jumpToCurrentPage) def setRenderedImage(self, page_no, image): """ takes a QImage and sets pixmap of the specified page when number of rendered pages exceeds a certain number, old page image is deleted to save memory """ debug("Set Rendered Image :", page_no) self.pages[page_no - 1].setPageData(page_no, QPixmap.fromImage(image), self.doc.page(page_no - 1)) # Request to render next page if self.current_page <= page_no < (self.current_page + self.max_preload - 2): if (page_no + 2 not in self.rendered_pages) and (page_no + 2 <= self.pages_count): self.rendered_pages.append(page_no + 2) self.renderRequested.emit(page_no + 2, self.pages[page_no + 1].dpi) # Replace old rendered pages with blank image if len(self.rendered_pages) > 10: cleared_page_no = self.rendered_pages.pop(0) debug("Clear Page :", cleared_page_no) self.pages[cleared_page_no - 1].clear() debug("Rendered Pages :", self.rendered_pages) def renderCurrentPage(self): """ Requests to render current page. if it is already rendered, then request to render next unrendered page """ requested = 0 for page_no in range(self.current_page, self.current_page + self.max_preload): if (page_no not in self.rendered_pages) and (page_no <= self.pages_count): self.rendered_pages.append(page_no) self.renderRequested.emit(page_no, self.pages[page_no - 1].dpi) requested += 1 debug("Render Requested :", page_no) if requested == 2: return def onMouseScroll(self, pos): """ It is called when vertical scrollbar value is changed. Get the current page number on scrolling, then requests to render""" index = self.verticalLayout.indexOf( self.frame.childAt(self.frame.width() / 2, pos)) if index == -1: return self.pageNoLabel.setText('<b>%i/%i</b>' % (index + 1, self.pages_count)) if self.scrollArea.verticalScrollBar().isSliderDown( ) or self.scroll_render_lock: return self.current_page = index + 1 self.renderCurrentPage() def onSliderRelease(self): self.onMouseScroll(self.scrollArea.verticalScrollBar().value()) def openFile(self): filename, sel_filter = QFileDialog.getOpenFileName( self, "Select Document to Open", "", "Portable Document Format (*.pdf);;All Files (*)") if filename != "": self.loadPDFfile(filename) def lockUnlock(self): if which("qpdf") == None: self.lockUnlockAction.setEnabled(False) QMessageBox.warning( self, "qpdf Required", "qpdf command not found.\nInstall qpdf program.") return if self.lockUnlockAction.text() == "Encrypt PDF": self.encryptPDF() return filename, ext = os.path.splitext(self.filename) new_name = filename + "-unlocked.pdf" proc = Popen([ "qpdf", "--decrypt", "--password="******"File Saved", "Successfully saved as\n" + basename) else: QMessageBox.warning(self, "Failed !", "Failed to save as unlocked") def encryptPDF(self): password, ok = QInputDialog.getText(self, "Lock PDF", "Enter Password :"******"": return filename, ext = os.path.splitext(self.filename) new_name = filename + "-locked.pdf" proc = Popen([ "qpdf", "--encrypt", password, password, '128', '--', self.filename, new_name ]) stdout, stderr = proc.communicate() if proc.returncode == 0: basename = os.path.basename(new_name) QMessageBox.information(self, "File Saved", "Successfully saved as\n" + basename) else: QMessageBox.warning(self, "Failed !", "Failed to save as Encrypted") def printFile(self): if which("quikprint") == None: QMessageBox.warning(self, "QuikPrint Required", "Install QuikPrint program.") return Popen(["quikprint", self.filename]) def exportToPS(self): width = self.doc.page(self.current_page - 1).pageSizeF().width() height = self.doc.page(self.current_page - 1).pageSizeF().height() filename, sel_filter = QFileDialog.getSaveFileName( self, "Select File to Save", os.path.splitext(self.filename)[0] + '.ps', "Adobe Postscript Format (*.ps)") if filename == '': return conv = self.doc.psConverter() conv.setPaperWidth(width) conv.setPaperHeight(height) conv.setOutputFileName(filename) conv.setPageList([i + 1 for i in range(self.pages_count)]) ok = conv.convert() if ok: QMessageBox.information(self, "Successful !", "File has been successfully exported") else: QMessageBox.warning(self, "Failed !", "Failed to export to Postscript") def exportPageToImage(self): dialog = ExportToImageDialog(self.current_page, self.pages_count, self) if dialog.exec_() == QDialog.Accepted: try: dpi = int(dialog.dpiEdit.text()) page_no = dialog.pageNoSpin.value() filename = os.path.splitext( self.filename)[0] + '-' + str(page_no) + '.jpg' page = self.doc.page(page_no - 1) if not page: return img = page.renderToImage(dpi, dpi) img.save(filename) QMessageBox.information(self, "Successful !", "Page has been successfully exported") except: QMessageBox.warning(self, "Failed !", "Failed to export to Image") def docInfo(self): info_keys = list(self.doc.infoKeys()) values = [self.doc.info(key) for key in info_keys] page_size = self.doc.page(self.current_page - 1).pageSizeF() page_size = "%s x %s pts" % (page_size.width(), page_size.height()) info_keys += ['Embedded FIles', 'Page Size'] values += [str(self.doc.hasEmbeddedFiles()), page_size] dialog = DocInfoDialog(self) dialog.setInfo(info_keys, values) dialog.exec_() def jumpToCurrentPage(self): """ this is used as a slot, to connect with a timer""" self.jumpToPage(self.current_page) def jumpToPage(self, page_num, top=0.0): """ scrolls to a particular page and position """ if page_num < 1: page_num = 1 elif page_num > self.pages_count: page_num = self.pages_count if not (0 < top < 1.0): top = 0 self.jumped_from = self.current_page self.current_page = page_num scrollbar_pos = self.pages[page_num - 1].pos().y() scrollbar_pos += top * self.pages[page_num - 1].height() self.scrollArea.verticalScrollBar().setValue(scrollbar_pos) def undoJump(self): if self.jumped_from == None: return self.jumpToPage(self.jumped_from) def goNextPage(self): if self.current_page == self.pages_count: return self.jumpToPage(self.current_page + 1) def goPrevPage(self): if self.current_page == 1: return self.jumpToPage(self.current_page - 1) def goFirstPage(self): self.jumpToPage(1) def goLastPage(self): self.jumpToPage(self.pages_count) def gotoPage(self): text = self.gotoPageEdit.text() if text == "": return self.jumpToPage(int(text)) self.gotoPageEdit.clear() self.gotoPageEdit.clearFocus() ###################### Zoom and Size Management ########################## def availableWidth(self): """ Returns available width for rendering a page """ dock_width = 0 if self.dockWidget.isHidden( ) else self.dockWidget.width() return self.width() - dock_width - 50 def resizePages(self): '''Resize all pages according to zoom level ''' page_dpi = self.zoom_levels[ self.zoomLevelCombo.currentIndex()] * SCREEN_DPI / 100 fixed_width = self.availableWidth() for i in range(self.pages_count): pg_width = self.doc.page(i).pageSizeF().width() # width in points pg_height = self.doc.page(i).pageSizeF().height() if self.zoomLevelCombo.currentIndex() == 0: # if fixed width dpi = 72.0 * fixed_width / pg_width else: dpi = page_dpi self.pages[i].dpi = dpi self.pages[i].setFixedSize(pg_width * dpi / 72.0, pg_height * dpi / 72.0) for page_no in self.rendered_pages: self.pages[page_no - 1].clear() self.rendered_pages = [] self.renderCurrentPage() def setZoom(self, index): """ Gets called when zoom level is changed""" self.scroll_render_lock = True # rendering on scroll is locked as set scroll position self.resizePages() QtCore.QTimer.singleShot(300, self.afterZoom) def zoomIn(self): index = self.zoomLevelCombo.currentIndex() if index == len(self.zoom_levels) - 1: return if index == 0: index = 3 self.zoomLevelCombo.setCurrentIndex(index + 1) self.setZoom(index + 1) def zoomOut(self): index = self.zoomLevelCombo.currentIndex() if index == 1: return if index == 0: index = 4 self.zoomLevelCombo.setCurrentIndex(index - 1) self.setZoom(index - 1) def afterZoom(self): scrolbar_pos = self.pages[self.current_page - 1].pos().y() self.scrollArea.verticalScrollBar().setValue(scrolbar_pos) self.scroll_render_lock = False ######### Search Text ######### def toggleFindMode(self, enable): if enable: self.findTextEdit.setText('') self.findTextEdit.setFocus() self.search_text = '' self.search_result_page = 0 elif self.search_result_page != 0: self.pages[self.search_result_page - 1].highlight_area = None self.pages[self.search_result_page - 1].updateImage() def findNext(self): """ search text in current page and next pages """ text = self.findTextEdit.text() if text == "": return # search from current page when text changed if self.search_text != text or self.search_result_page == 0: search_from_page = self.current_page else: search_from_page = self.search_result_page + 1 self.findTextRequested.emit(text, search_from_page, False) if self.search_result_page != 0: # clear previous highlights self.pages[self.search_result_page - 1].highlight_area = None self.pages[self.search_result_page - 1].updateImage() self.search_result_page = 0 self.search_text = text def findBack(self): """ search text in pages before current page """ text = self.findTextEdit.text() if text == "": return if self.search_text != text or self.search_result_page == 0: search_from_page = self.current_page else: search_from_page = self.search_result_page - 1 self.findTextRequested.emit(text, search_from_page, True) if self.search_result_page != 0: self.pages[self.search_result_page - 1].highlight_area = None self.pages[self.search_result_page - 1].updateImage() self.search_result_page = 0 self.search_text = text def onTextFound(self, page_no, areas): self.pages[page_no - 1].highlight_area = areas self.search_result_page = page_no if self.pages[page_no - 1].pixmap(): self.pages[page_no - 1].updateImage() first_result_pos = areas[0].y() / self.doc.page(page_no - 1).pageSize().height() self.jumpToPage(page_no, first_result_pos) ######### Cpoy Text to Clip Board ######### def toggleCopyText(self, checked): self.frame.enableCopyTextMode(checked) def copyText(self, page_no, top_left, bottom_right): zoom = self.pages[page_no - 1].height() / self.doc.page(page_no - 1).pageSize().height() # Copy text to clipboard text = self.doc.page(page_no - 1).text( QtCore.QRectF(top_left / zoom, bottom_right / zoom)) QApplication.clipboard().setText(text) self.copyTextAction.setChecked(False) self.toggleCopyText(False) ########## Other Functions ########## def getOutlines(self, doc): toc = doc.toc() if not toc: self.dockWidget.hide() return self.dockWidget.show() outline_model = QStandardItemModel(self) parent_item = outline_model.invisibleRootItem() node = toc.firstChild() loadOutline(doc, node, parent_item) self.treeView.setModel(outline_model) if parent_item.rowCount() < 4: self.treeView.expandToDepth(0) self.treeView.setHeaderHidden(True) self.treeView.header().setSectionResizeMode(0, 1) self.treeView.header().setSectionResizeMode(1, 3) self.treeView.header().setStretchLastSection(False) def onOutlineClick(self, m_index): page_num = self.treeView.model().data(m_index, QtCore.Qt.UserRole + 1) top = self.treeView.model().data(m_index, QtCore.Qt.UserRole + 2) if not page_num: return self.jumpToPage(page_num, top) def showStatus(self, url): if url == "": self.statusbar.hide() return self.statusbar.setText(url) self.statusbar.adjustSize() self.statusbar.move(0, self.height() - self.statusbar.height()) self.statusbar.show() def resizeEvent(self, ev): QMainWindow.resizeEvent(self, ev) if self.filename == '': return if self.zoomLevelCombo.currentIndex() == 0: self.resize_page_timer.start(200) def onWindowResize(self): for i in range(self.pages_count): self.pages[ i].annots_listed = False # Clears prev link annotation positions self.resizePages() wait(300) self.jumpToCurrentPage() if not self.isMaximized(): self.settings.setValue("WindowWidth", self.width()) self.settings.setValue("WindowHeight", self.height()) def saveFileData(self): if self.filename != '': filename = collapseUser(self.filename) if filename in self.history_filenames: index = self.history_filenames.index(filename) self.history_page_no[index] = self.current_page else: self.history_filenames.insert(0, filename) self.history_page_no.insert(0, self.current_page) if filename in self.recent_files: self.recent_files.remove(filename) self.recent_files.insert(0, filename) def closeEvent(self, ev): """ Save all settings on window close """ self.saveFileData() self.settings.setValue("OffsetX", self.geometry().x() - self.x()) self.settings.setValue("OffsetY", self.geometry().y() - self.y()) self.settings.setValue("ZoomLevel", self.zoomLevelCombo.currentIndex()) self.settings.setValue("HistoryFileNameList", self.history_filenames[:100]) self.settings.setValue("HistoryPageNoList", self.history_page_no[:100]) self.settings.setValue("RecentFiles", self.recent_files[:10]) return QMainWindow.closeEvent(self, ev) def onAppQuit(self): """ Close running threads """ loop1 = QtCore.QEventLoop() loop2 = QtCore.QEventLoop() self.thread1.finished.connect(loop1.quit) self.thread2.finished.connect(loop2.quit) self.thread1.quit() loop1.exec_() self.thread2.quit() loop2.exec_()
class CurrentMusicShort(QFrame): """用于显示当前歌曲的简单信息。""" def __init__(self, parent=None): super(CurrentMusicShort, self).__init__() self.parent = parent self.setObjectName('short') self.mousePos = None self.setLabels() # self.setButtons() self.setLayouts() self.init() # 布局。 def setLabels(self): self.musicName = QLabel(self) self.musicName.adjustSize() self.musicAuthor = QLabel(self) self.musicPic = PicLabel('resource/no_music.png', 64, 64) self.musicPic.setObjectName("musicPic") self.musicMask = PicLabel('resource/expand.png', 64, 64) self.musicMask.hide() # 设置背景透明。 self.musicMask.setStyleSheet( 'QLabel {background-color: rgba(0, 0, 0, 50%;)}') # 遮罩层属于musicPic, 用布局简单弄一下即可。 self.musicLayout = VBoxLayout(self.musicPic) self.musicLayout.addWidget(self.musicMask) def setLayouts(self): """布局。""" self.mainLayout = QHBoxLayout() self.mainLayout.setContentsMargins(0, 0, 0, 0) self.musicInfo = QVBoxLayout() self.mainLayout.setContentsMargins(0, 0, 0, 0) self.musicInfo.addWidget(self.musicName) self.musicInfo.addWidget(self.musicAuthor) self.mainLayout.addWidget(self.musicPic) self.mainLayout.addLayout(self.musicInfo) self.mainLayout.setStretch(0, 1) self.mainLayout.setStretch(1, 2) self.setLayout(self.mainLayout) # 功能. def init(self): """默认情况下的显示,包括音乐图片,音乐名和音乐作者。""" self.musicName.setText("Enjoy it") self.musicAuthor.setText("Enjoy it") # 事件。 def enterEvent(self, event): if not self.musicMask.isVisible(): self.musicMask.show() def leaveEvent(self, event): if self.musicMask.isVisible(): self.musicMask.hide()
class MainWindow(QMainWindow): # noinspection PyArgumentList def __init__(self): super().__init__() self.currentImage = '' self.init_ui() def init_ui(self): self.setGeometry(300, 300, 350, 300) self.center() self.image_label = QLabel() self.image_label.setBackgroundRole(QPalette.Dark) self.image_label.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.image_label.setScaledContents(True) self.scroll_area = QScrollArea() self.scroll_area.setBackgroundRole(QPalette.Dark) self.scroll_area.setWidget(self.image_label) self.setCentralWidget(self.scroll_area) self.create_actions() self.init_tool_bar() app_icon = QIcon(os.path.join(IMAGES_PATH, 'photos.png')) menubar = self.menuBar() file_menu = menubar.addMenu('File') file_menu.addAction(self.open_file) file_menu.addAction(self.save_file) self.enable_actions(False) self.setWindowTitle('Image processing') self.setWindowIcon(app_icon) self.statusBar().showMessage('Ready') # noinspection PyArgumentList def create_actions(self): open_icon = QIcon(os.path.join(IMAGES_PATH, 'folder-10.png')) save_icon = QIcon(os.path.join(IMAGES_PATH, 'save.png')) gray_icon = QIcon(os.path.join(IMAGES_PATH, 'picture-gray.png')) sepia_icon = QIcon(os.path.join(IMAGES_PATH, 'picture-sepia.png')) bw_icon = QIcon(os.path.join(IMAGES_PATH, 'picture_bw.png')) bw_icon_2 = QIcon(os.path.join(IMAGES_PATH, 'picture_bw_2.png')) inv_icon = QIcon(os.path.join(IMAGES_PATH, 'picture_inv.png')) orig_icon = QIcon(os.path.join(IMAGES_PATH, 'picture.png')) scale_icon = QIcon(os.path.join(IMAGES_PATH, '020-scale.png')) crop_icon = QIcon(os.path.join(IMAGES_PATH, '018-crop.png')) self.open_file = QAction( open_icon, '&Open...', self, shortcut='Ctrl+O', triggered=self.dialog_open, ) self.save_file = QAction(save_icon, '&Save as...', self, shortcut='Ctrl+S', triggered=self.dialog_save) self.set_gray_action = QAction(gray_icon, 'Gray tones', self, triggered=self.set_gray) self.set_bw_action = QAction(bw_icon, 'Black and white', self, triggered=self.set_bw) self.set_bw2_action = QAction(bw_icon_2, 'Black and white method 2', self, triggered=self.set_bw2) self.set_sepia_action = QAction(sepia_icon, 'Sepia', self, triggered=self.set_sepia) self.set_inverted_action = QAction(inv_icon, 'Inverted', self, triggered=self.set_inverted) self.set_original_action = QAction(orig_icon, 'Original', self, triggered=self.set_original) self.scale_action = QAction(scale_icon, 'Scale', self, triggered=self.scale) self.crop_action = QAction(crop_icon, 'Crop', self, triggered=self.crop) def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def init_tool_bar(self): self.toolbar = self.addToolBar('Image tools') self.toolbar.addAction(self.set_original_action) self.toolbar.addAction(self.set_gray_action) self.toolbar.addAction(self.set_bw_action) self.toolbar.addAction(self.set_bw2_action) self.toolbar.addAction(self.set_sepia_action) self.toolbar.addAction(self.set_inverted_action) self.toolbar.addAction(self.scale_action) self.toolbar.addAction(self.crop_action) def enable_actions(self, state): for action in self.toolbar.actions(): action.setEnabled(state) def dialog_open(self): fname = QFileDialog.getOpenFileName( self, 'Open file', os.path.expanduser(''), 'Images (*.png *.xpm *.jpg);;All files (*.*)')[0] if fname: self.statusBar().showMessage('Selected file: {}'.format(fname)) print(fname) if os.path.isfile(fname): self.pixmap = QPixmap(fname) self.currentImage = fname self.image_label.setPixmap(self.pixmap) self.adjust_size() self.enable_actions(True) def dialog_save(self): fname = QFileDialog.getSaveFileName( self, 'Save as', os.path.expanduser(''), 'Images (*.png *.xpm *.jpg);;All files (*.*)')[0] if fname: self.statusBar().showMessage('Saved file as: {}'.format(fname)) print(fname) self.pixmap.save(fname) self.currentImage = fname def adjust_size(self): self.image_label.adjustSize() self.resize(self.image_label.width() + 25, self.image_label.height() + 60) def crop(self): if os.path.isfile(self.currentImage): self.pixmap = ImageEditor(self.currentImage).crop() self.image_label.setPixmap(self.pixmap) self.adjust_size() def scale(self): if os.path.isfile(self.currentImage): items = ('0.5', '0.7', '1.5') item, okPressed = QInputDialog.getItem(self, 'Resize image', 'Scale factor:', items, 0, False) if okPressed and item: print(item) self.pixmap = ImageEditor(self.currentImage).resize(item) self.image_label.setPixmap(self.pixmap) self.adjust_size() def set_bw(self): if os.path.isfile(self.currentImage): self.pixmap = ImageEditor(self.currentImage).bw() self.image_label.setPixmap(self.pixmap) self.adjust_size() def set_bw2(self): if os.path.isfile(self.currentImage): self.pixmap = ImageEditor(self.currentImage).bw2() self.image_label.setPixmap(self.pixmap) self.adjust_size() def set_inverted(self): if os.path.isfile(self.currentImage): self.pixmap = ImageEditor(self.currentImage).inverted() self.image_label.setPixmap(self.pixmap) self.adjust_size() def set_sepia(self): if os.path.isfile(self.currentImage): self.pixmap = ImageEditor(self.currentImage).sepia() self.image_label.setPixmap(self.pixmap) self.adjust_size() def set_original(self): if os.path.isfile(self.currentImage): self.pixmap = QPixmap(self.currentImage) self.image_label.setPixmap(self.pixmap) self.adjust_size() def set_gray(self): if os.path.isfile(self.currentImage): self.pixmap = ImageEditor(self.currentImage).gray() self.image_label.setPixmap(self.pixmap) self.adjust_size()
class MyFirstGUI(QtWidgets.QDialog): file_select = '' def __init__(self): # Initializing QDialog and locking the size at a certain value super(MyFirstGUI, self).__init__() self.setFixedSize(1200, 670) self.fileName = "test.csv" self.model = QtGui.QStandardItemModel(self) self.setWindowTitle("HYBRID LOGISTIC REGRESSION ON TWITTER POST") #--------------DIVIDER-------------------- self.divider_top = QGroupBox(self) self.divider_top.resize(1200, 4) self.divider_top.move(1, 75) self.divider_sideleft = QGroupBox(self) self.divider_sideleft.resize(4, 500) self.divider_sideleft.move(500, 75) self.divider_sideright = QGroupBox(self) self.divider_sideright.resize(4, 500) self.divider_sideright.move(700, 75) #---------------BUTTONS AND TEXT----------------------------- self.lbl_test = QLabel('TEST_SIZE', self) self.lbl_test.move(30, 30) self.txt_test = QLineEdit(self) self.txt_test.move(100, 30) self.sentiment = QPushButton('SENTIMENT', self) self.sentiment.move(700, 20) self.sentiment.resize(100, 50) self.sentiment.clicked.connect(self.senti) self.generate = QPushButton('GENERATE', self) self.generate.setToolTip('Generate The Algorithm') self.generate.move(820, 20) self.generate.resize(100, 50) #self.generate.setEnabled(False) self.generate.clicked.connect(self.on_click) self.clear = QPushButton('CLEAR', self) self.clear.move(940, 20) self.clear.resize(100, 50) self.clear.setEnabled(False) self.clear.clicked.connect(self.on_clear) self.exitui = QPushButton('EXIT', self) self.exitui.move(1050, 20) self.exitui.resize(100, 50) self.exitui.clicked.connect(self.terminate) #----GRAPH BOX FOR OLD ALGORITHM-------- self.lbl_numb = QLabel('OLD ALGORITHM', self) self.lbl_numb.move(150, 100) self.oldalgo_GraphBox = QGroupBox(self) self.oldalgo_GraphBox.resize(350, 250) self.oldalgo_GraphBox.move(30, 120) self.lbl_accurateold = QLabel(self) self.lbl_accurateold.setText('ACCURACY: ') self.lbl_accurateold.move(70, 380) self.lbl_confuseold = QLabel(self) self.lbl_confuseold.setText('CONFUSION MATRIX') self.lbl_confuseold.move(390, 200) #------------------------------------------------- #----GRAPH BOX FOR NEW ALGORITHM-------- self.newalgo_GraphBox = QtWidgets.QGroupBox('', self) self.newalgo_GraphBox.resize(350, 250) self.newalgo_GraphBox.move(830, 120) self.lbl_numb = QLabel(self) self.lbl_numb.setText('NEW ALGO') self.lbl_numb.move(950, 100) self.lbl_accuratenew = QLabel(self) self.lbl_accuratenew.setText('ACCURACY: ') self.lbl_accuratenew.move(850, 380) self.lbl_confusenew = QLabel(self) self.lbl_confusenew.setText('CONFUSION MATRIX') self.lbl_confusenew.move(720, 200) #--------------------RESULT FOR OLD ALGO------------------------ self.lbl_tally_positive = QLabel(self) self.lbl_tally_positive.setText('POSITIVE: ') self.lbl_tally_positive.move(50, 430) self.lbl_tally_neutral = QLabel(self) self.lbl_tally_neutral.setText('NEUTRAL: ') self.lbl_tally_neutral.move(180, 430) self.lbl_tally_negative = QLabel(self) self.lbl_tally_negative.setText('NEGATIVE: ') self.lbl_tally_negative.move(280, 430) self.lbl_tally_overall = QLabel(self) self.lbl_tally_overall.setText('OVERALL RESULT: ') self.lbl_tally_overall.move(150, 470) #--------------------RESULT FOR NEW ALGO------------------------ self.lbl_tally_hybpositive = QLabel(self) self.lbl_tally_hybpositive.setText('POSITIVE: ') self.lbl_tally_hybpositive.move(800, 430) self.lbl_tally_hybneutral = QLabel(self) self.lbl_tally_hybneutral.setText('NEUTRAL: ') self.lbl_tally_hybneutral.move(950, 430) self.lbl_tally_hybnegative = QLabel(self) self.lbl_tally_hybnegative.setText('NEGATIVE: ') self.lbl_tally_hybnegative.move(1080, 430) self.lbl_tally_hyboverall = QLabel(self) self.lbl_tally_hyboverall.setText('OVERALL RESULT: ') self.lbl_tally_hyboverall.move(940, 470) #-------------------------------------------- #----------------------TABLE FOR THE LIST OF GATHERED TWEETS------------------- self.tableWidget = QtWidgets.QTableWidget(self) self.tableWidget.resize(1100, 150) self.tableWidget.move(40, 500) self.tableWidget.setColumnCount(14) self.tableWidget.setObjectName("tableWidget") self.tableWidget.setHorizontalHeaderLabels([ "ID", "TWEETS", "TOKENIZED", "STOP WORDS", "STEMMED", "POLARITY", "SUBJECTIVITY", "SENTIMENT", "BASELINE VALUE", "BASELINE SENTIMENT", "BASELINE RESULT", "HYBRID VALUE", "HYBRID SENTIMENT", "HYBRID RESULT" ]) self.tableWidget.doubleClicked.connect(self.getSelectedItemData) self.tableWidget.setSelectionBehavior(self.tableWidget.SelectRows) def terminate(self): exit() def getSelectedItemData(self): paths = [] selected = self.tableWidget.selectedItems() if selected: for item in selected: if item.column() == 1: tweet = item.data(0) if item.column() == 5: polar = item.data(0) if item.column() == 6: subject = item.data(0) if item.column() == 7: sentim = item.data(0) if item.column() == 8: base_val = item.data(0) if item.column() == 9: base_sent = item.data(0) if item.column() == 10: base_res = item.data(0) if item.column() == 11: hyb_val = item.data(0) if item.column() == 12: hyb_sent = item.data(0) if item.column() == 13: hyb_res = item.data(0) print(paths) msg = QMessageBox() msg.setIcon(QMessageBox.Information) message = 'SENTIMENT: ' + sentim result_message = 'BASELINE VALUE: ' + base_val + '\n' + 'BASELINE SENTIMENT: ' + base_sent + "\n" + 'BASELINE RESULT: ' + base_res + "\n" + "======================================" + "\n" + 'HYBRID VALUE: ' + hyb_val + '\n' + 'HYBRID SENTIMENT: ' + hyb_sent + "\n" + 'HYBRID RESULT: ' + hyb_res msg.setText(tweet) msg.setInformativeText(message) msg.setWindowTitle("LOGISTIC REGRESSION") msg.setDetailedText(result_message) msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) retval = msg.exec_() #print ("value of pressed message box button:", retval) #-------------------GENERATE SENTIMENT---------------------------------- def senti(self, event): try: self.file_select = self.openFileNameDialog(self) self.file_train = self.file_select self.getfile = self.file_train if self.file_train == "no file": pass else: from PREPREOCESS_SENTIMENT import Sentiment_process import PREPREOCESS_SENTIMENT self.pass_message = PREPREOCESS_SENTIMENT.Sentiment_process( self.getfile) self.sentiment_result = QMessageBox() self.sentiment_result.setWindowTitle("LOGISTIC REGRESSION") self.sentiment_result.setText("SENTIMENT TWEETS COMPLETE") self.sentiment_result.setIcon(QMessageBox.Information) self.y = self.sentiment_result.exec_() except Exception as e: print(e) self.result = QMessageBox() self.result.setWindowTitle("LOGISTIC REGRESSION") self.result.setText('ERROR') self.result.setIcon(QMessageBox.Warning) self.x = self.result.exec_() #---------------GENERATING THE ALGORITHM----------------------------------- def on_click(self, event): try: self.file_select = self.openFileNameDialog(self) self.file_cv = self.file_select self.getfile = self.file_cv file_check = pathlib.Path(self.file_cv) if self.txt_test.text() == "": self.result = QMessageBox() self.result.setWindowTitle("LOGISTIC REGRESSION") self.result.setText('PLEASE PUT THE VALUE OF THE TEST SIZE') self.result.setIcon(QMessageBox.Warning) self.x = self.result.exec_() else: self.test_size = self.txt_test.text() self.NoOftest = float(self.test_size) self.test_num = self.NoOftest if file_check.exists(): if self.NoOftest > 0.90: self.result = QMessageBox() self.result.setWindowTitle("LOGISTIC REGRESSION") self.result.setText( 'PLEASE LIMIT THE TEST SIZE VALUE NOT MORE THAN 0.90 AND EQUAL TO 0.0' ) self.result.setIcon(QMessageBox.Warning) self.x = self.result.exec_() else: from BASELINE import baseline_algo import BASELINE self.pass_message = BASELINE.baseline_algo( self.getfile, self.test_num) #-----------------BASELINE RESULTS------------------------ final_accurate = str(BASELINE.percentage) final_pos = str(BASELINE.posi) final_neu = str(BASELINE.neut) final_neg = str(BASELINE.nega) final_cm = str(BASELINE.confuse) final_report = str(BASELINE.reports) post_accurate = 'ACCURACY: ' + final_accurate post_pos = 'POSITIVE: ' + final_pos post_neu = 'NEUTRAL: ' + final_neu post_neg = 'NEGATIVE: ' + final_neg post_overall = 'OVERALL RESULT: ' + BASELINE.overall post_cm = 'CONFUSION MATRIX' + '\n' + final_cm #-----PLOT GRAPH FOR OLD----------------- ploted = BASELINE.plots self.m = MplCanvas(self, width=5, height=4) self.m.axes.plot(ploted) self.layout_oldalgo = QtWidgets.QVBoxLayout() self.layout_oldalgo.addWidget(self.m) self.oldalgo_GraphBox.setLayout(self.layout_oldalgo) self.lbl_accurateold.setText(post_accurate) self.lbl_accurateold.adjustSize() self.lbl_tally_positive.setText(post_pos) self.lbl_tally_positive.adjustSize() self.lbl_tally_neutral.setText(post_neu) self.lbl_tally_neutral.adjustSize() self.lbl_tally_negative.setText(post_neg) self.lbl_tally_negative.adjustSize() self.lbl_tally_overall.setText(post_overall) self.lbl_tally_overall.adjustSize() from LOGSITC_REGRESSION_WITH_HYBRID import logistic_regression import LOGSITC_REGRESSION_WITH_HYBRID self.passed_message = LOGSITC_REGRESSION_WITH_HYBRID.logistic_regression( self.getfile, self.test_num) #-----------------HYBRID RESULTS------------------------ final_hyb_accurate = str( LOGSITC_REGRESSION_WITH_HYBRID.percentage) final_hyb_cm = str( LOGSITC_REGRESSION_WITH_HYBRID.confuse) final_hyb_report = str( LOGSITC_REGRESSION_WITH_HYBRID.reports) post_hyb_accurate = 'ACCURACY: ' + final_hyb_accurate post_hyb_cm = 'CONFUSION MATRIX' + '\n' + final_hyb_cm final_hybpos = str(LOGSITC_REGRESSION_WITH_HYBRID.posi) final_hybneu = str(LOGSITC_REGRESSION_WITH_HYBRID.neut) final_hybneg = str(LOGSITC_REGRESSION_WITH_HYBRID.nega) post_hybpos = 'POSITIVE: ' + final_hybpos post_hybneu = 'NEUTRAL: ' + final_hybneu post_hybneg = 'NEGATIVE: ' + final_hybneg post_hyboverall = 'OVERALL RESULT: ' + LOGSITC_REGRESSION_WITH_HYBRID.overall #----------------GRAPH FOR NEW----------------------------- hyb_ploted = LOGSITC_REGRESSION_WITH_HYBRID.plots self.n = newMplCanvas(self, width=5, height=4) self.n.axes.plot(hyb_ploted) self.layout_newalgo = QtWidgets.QVBoxLayout() self.layout_newalgo.addWidget(self.n) self.newalgo_GraphBox.setLayout(self.layout_newalgo) #------------------TEXT CHANGED WITH THE RESULT---------------------------- self.lbl_accuratenew.setText(post_hyb_accurate) self.lbl_accuratenew.adjustSize() #-------------HYBRID--------------------- self.lbl_tally_hybpositive.setText(post_hybpos) self.lbl_tally_hybpositive.adjustSize() self.lbl_tally_hybneutral.setText(post_hybneu) self.lbl_tally_hybneutral.adjustSize() self.lbl_tally_hybnegative.setText(post_hybneg) self.lbl_tally_hybnegative.adjustSize() self.lbl_tally_hyboverall.setText(post_hyboverall) self.lbl_tally_hyboverall.adjustSize() self.lbl_confuseold.setText(post_cm) self.lbl_confuseold.adjustSize() self.lbl_confusenew.setText(post_hyb_cm) self.lbl_confusenew.adjustSize() self.loaddata() self.tableWidget.setHorizontalHeaderLabels([ "ID", "TWEETS", "TOKENIZED", "STOP WORDS", "STEMMED", "POLARITY", "SUBJECTIVITY", "SENTIMENT", "BASELINE VALUE", "BASELINE SENTIMENT", "BASELINE RESULT", "HYBRID VALUE", "HYBRID SENTIMENT", "HYBRID RESULT" ]) import os if os.path.exists("temp_filebase.csv"): os.remove("temp_filebase.csv") else: print("The file does not exist") if os.path.exists("temp_file.csv"): os.remove("temp_file.csv") else: print("The file does not exist") #----------------MESSAGE BOX------------------------- final_results = final_report + "\n" + "------------------------------" + "\n" + "WITH HYBRID" + "\n" + final_hyb_report self.result = QMessageBox() self.result.setWindowTitle("LOGISTIC REGRESSION") self.result.setText(final_results) self.result.setIcon(QMessageBox.Information) self.clear.setEnabled(True) self.x = self.result.exec_() else: self.result = QMessageBox() self.result.setWindowTitle("LOGISTIC REGRESSION") self.result.setText( 'FILE NOT FOUND, PLEASE CLICK THE SENTIMENT BUTTON TO CREATE THE TEST.CSV' ) self.result.setIcon(QMessageBox.Information) self.x = self.result.exec_() except Exception as e: print(e) self.result = QMessageBox() self.result.setWindowTitle("LOGISTIC REGRESSION") self.result.setText('ERROR') self.result.setIcon(QMessageBox.Warning) self.x = self.result.exec_() #-----------------FOR THE TABLE VIEW-------------------- def loaddata(self): import MySQLdb mydb = MySQLdb.connect(host="127.0.0.1", user="******", password="", database="logitregression_data") mycursor = mydb.cursor() query = "SELECT baseline.ID, baseline.TWEETS,baseline.TOKENIZED,baseline.STOP_WORDS,baseline.STEMMED,baseline.POLARITY,baseline.SUBJECTIVITY, baseline.SENTIMENT,baseline_logitval.BASE_VALUE,baseline_logitval.BASE_SENTIMENT,baseline_logitval.BASE_RESULT, hybrid_logitval.HYB_VALUE,hybrid_logitval.HYB_SENTIMENT,hybrid_logitval.HYB_RESULT FROM baseline LEFT JOIN baseline_logitval on baseline.ID = baseline_logitval.BASE_ID LEFT JOIN hybrid_logitval ON baseline.ID = hybrid_logitval.HYB_ID WHERE baseline_logitval.BASE_VALUE IS NOT NULL" mycursor.execute(query) result = mycursor.fetchall() self.tableWidget.setRowCount(0) for row_number, row_data in enumerate(result): print(row_number) self.tableWidget.insertRow(row_number) for column_number, data in enumerate(row_data): #print(column_number) self.tableWidget.setItem(row_number, column_number, QTableWidgetItem(str(data))) def on_clear(self): #-----PLOT GRAPH FOR OLD----------------- self.m.setHidden(True) #----------------GRAPH FOR NEW----------------------------- self.n.setHidden(True) #------------------TEXT CHANGED WITH THE RESULT---------------------------- self.lbl_accuratenew.setText('ACCURACY: ') self.lbl_accuratenew.adjustSize() self.lbl_accurateold.setText('ACCURACY: ') self.lbl_accurateold.adjustSize() self.lbl_tally_positive.setText('POSITIVE: ') self.lbl_tally_positive.adjustSize() self.lbl_tally_neutral.setText('NEUTRAL: ') self.lbl_tally_neutral.adjustSize() self.lbl_tally_negative.setText('NEGATIVE: ') self.lbl_tally_negative.adjustSize() self.lbl_tally_overall.setText('OVERALL RESULT: ') self.lbl_tally_overall.adjustSize() #-------------HYBRID-------------------- self.lbl_tally_hybpositive.setText('POSITIVE: ') self.lbl_tally_hybpositive.adjustSize() self.lbl_tally_hybneutral.setText('NEUTRAL: ') self.lbl_tally_hybneutral.adjustSize() self.lbl_tally_hybnegative.setText('NEGATIVE: ') self.lbl_tally_hybnegative.adjustSize() self.lbl_tally_hyboverall.setText('OVERALL RESULT: ') self.lbl_tally_hyboverall.adjustSize() self.lbl_confuseold.setText('CONFUSION MATRIX') self.lbl_confuseold.adjustSize() self.lbl_confusenew.setText('CONFUSION MATRIX') self.lbl_confusenew.adjustSize() self.clear.setEnabled(False) self.layout_oldalgo.deleteLater() self.layout_newalgo.deleteLater() self.tableWidget.clear() self.tableWidget.setHorizontalHeaderLabels([ "ID", "TWEETS", "TOKENIZED", "STOP WORDS", "STEMMED", "POLARITY", "SUBJECTIVITY", "SENTIMENT", "BASELINE VALUE", "BASELINE SENTIMENT", "BASELINE RESULT", "HYBRID VALUE", "HYBRID SENTIMENT", "HYBRID RESULT" ]) #-------------------OPEN FILES FOR DATA------------------------ def openFileNameDialog(self, event): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getOpenFileName(self, "Open File", "", "Excel Files (*.csv)", options=options) if fileName: self.file_select = fileName return self.file_select else: self.file_select = "no file" return self.file_select
class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): # Init corpus global corpus_list corpus_list = [[]] time0 = time.time() # corpus_list = get_links(corpus_list) corpus_list = get_text_local(corpus_list) time1 = time.time() print('elapsed time: %d' % (time1-time0)) print(len(corpus_list)) # Make components: self.lbl = QLabel("Your text will be displayed here", self) self.combo1_lbl = QLabel("Author 1", self) self.combo2_lbl = QLabel("Author 2", self) self.combo3_lbl = QLabel("Technique", self) self.combo1 = QComboBox(self) self.combo1.addItem("Jane Austen") self.combo1.addItem("G.K. Chesterton") self.combo1.addItem("William Shakespeare") self.combo1.addItem("Sir Arthur Conan Doyle") self.combo1.addItem("Fyodor Dostoyevsky") self.combo2 = QComboBox(self) self.combo2.addItem("Jane Austen") self.combo2.addItem("G.K. Chesterton") self.combo2.addItem("William Shakespeare") self.combo2.addItem("Sir Arthur Conan Doyle") self.combo2.addItem("Fyodor Dostoyevsky") self.combo3 = QComboBox(self) self.combo3.addItem("NLTK-2gram (No mix, Author 1 only)") self.combo3.addItem("Custom-2gram (No mix, Author 1 only)") self.combo3.addItem("Markov Chain (No mix, Author 1 only)") self.combo3.addItem("NLTK-2gram mix") self.combo3.addItem("Custom-2gram mix") self.combo3.addItem("Markov Chain mix") self.a1_lbl = QLabel("Author 1", self) self.a2_lbl = QLabel("Author 2", self) self.slider = QSlider(self) self.slider.setOrientation(Qt.Horizontal) self.slider.setFocusPolicy(Qt.StrongFocus) self.slider.setTickPosition(QSlider.TicksBothSides) self.slider.setTickInterval(11) self.slider.setSingleStep(1) self.slider.setMinimum(0) self.slider.setMaximum(100) self.slider.setValue(50) self.button = QPushButton("Generate", self) # Add to layout grid = QGridLayout() grid.addWidget(self.combo1_lbl, 0, 0) grid.addWidget(self.combo2_lbl, 1, 0) grid.addWidget(self.combo3_lbl, 2, 0) grid.addWidget(self.combo1, 0, 1) grid.addWidget(self.combo2, 1, 1) grid.addWidget(self.combo3, 2, 1) grid.addWidget(self.a1_lbl, 3,0) grid.addWidget(self.slider, 3,1) grid.addWidget(self.a2_lbl, 3,2) grid.addWidget(self.button, 4,1) grid.addWidget(self.lbl,5,1) self.setLayout(grid) self.button.clicked.connect(self.onClick) self.setGeometry(200, 200, 500, 500) self.setWindowTitle('Generate text') self.show() def onClick(self): global corpus_list technique = ['NLTK-2gram (No mix, Author 1 only)', 'Custom-2gram (No mix, Author 1 only)', 'Markov Chain (No mix, Author 1 only)', 'NLTK-2gram mix', 'Custom-2gram mix', 'Markov Chain mix'] print("button pushed") print(self.combo1.currentText()) print(self.combo2.currentText()) author1_index = authors.index(self.combo1.currentText()) author2_index = authors.index(self.combo2.currentText()) technique_index = technique.index(self.combo3.currentText()) ratio = self.slider.value() text = '' print('First index: ', author1_index) if technique_index == 0: text = nltk_2gram(author1_index) elif technique_index == 1: text = custom_2gram(author1_index) elif technique_index == 2: text = markov_chain(author1_index) elif technique_index == 3: text = nltk_2gram_mix(author1_index, author2_index, ratio) elif technique_index == 4: text = custom_2gram_mix(author1_index, author2_index, ratio) else: text = markov_chain_mix(author1_index, author2_index, ratio) self.lbl.setText(text) self.lbl.setWordWrap(True); self.lbl.adjustSize()
class Example(QWidget): """"Creation de la classe qui va gerer la fenetre creation des methodes evenements""" def __init__(self): #constructeur super().__init__() self.initUI() def initUI(self): #creation des labels nom = QLabel('Nom') prenom = QLabel('Prenom') commentaire = QLabel('Commentaire') #creation des champs d'entree de texte nomEdit = QLineEdit() prenomEdit = QLineEdit() #creation d'un champ d'entree multiligne commentaireEdit = QTextEdit() #creation des boutons okButton = QPushButton("OK") quitButton = QPushButton("Quitter") #creation d'un layout horizontal hbox = QHBoxLayout() hbox.addStretch(1) #ajout des widget dans le layout hbox.addWidget(okButton) hbox.addWidget(quitButton) #connexion du l'action de fermeture de la fenetre quitButton.clicked.connect(QCoreApplication.instance().quit) #creation d'un layout verticale vbox = QVBoxLayout() vbox.addStretch(1) #creation d'une grid layout grid = QGridLayout() grid.setSpacing(10) #Postionnement des differents elements dans le grid layout grid.addWidget(nom, 1, 0) grid.addWidget(nomEdit, 1, 1) grid.addWidget(prenom, 2, 0) grid.addWidget(prenomEdit, 2, 1) grid.addWidget(commentaire, 3, 0) grid.addWidget(commentaireEdit, 3, 1, 5, 1) #Creation de la liste deroulante combo = QComboBox(self) #On ajoute les differents elements pour la liste deroulante combo.addItem("Stylo") combo.addItem("Feutre") combo.addItem("Craie") combo.addItem("Chocolat") combo.addItem("Panda") #ajout de la liste deroulante dans la grid layout grid.addWidget(combo, 8, 0) #creation du label qui sera mise a jour lors de la selection de la liste deroulante self.label = QLabel("Stylo", self) #ajout du label dans la grille grid.addWidget(self.label, 8,1) #On connecte la mise a jour du texte a la selection de la liste combo.activated[str].connect(self.onActivated) #On ajoute la grid layout et le layout horizontal dans le layout vertical vbox.addLayout(grid) vbox.addLayout(hbox) #on met en place le layout self.setLayout(vbox) #mise a jour des fenetres self.setGeometry(300, 300, 350, 300) self.setWindowTitle('PC2') self.show() def onActivated(self, text): #methode qui fera la mise a jour du label a la selection dans la liste self.label.setText(text) self.label.adjustSize() print(text) def keyPressEvent(self, e): #methode qui surcharge l'appuie d'une touche du clavier if e.key() == Qt.Key_Escape: #on ferme la fenetre lors de l'appuie du bouton Esc self.close()
class Simple(QMainWindow): x = 'SiO2' y = ['Al2O3', 'MgO', 'FeO', 'CaO', 'Na2O', 'TiO2', 'K2O', 'P2O5'] SR = 'Strike' MR = 'Strike' def __init__(self): super().__init__() self.initUI() def initUI(self): Tas = QPushButton("Tas-1986", self) Tas.move(80, 30) Tas.clicked.connect(self.Tas) TasW = QPushButton("Tas Wilson", self) TasW.move(250, 30) TasW.clicked.connect(self.TasW) TasV = QPushButton("Tas Volcano", self) TasV.move(420, 30) TasV.clicked.connect(self.TasV) TasI = QPushButton("Tas Intrusion", self) TasI.move(590, 30) TasI.clicked.connect(self.TasI) Ree = QPushButton("Ree", self) Ree.move(80, 80) Ree.clicked.connect(self.Ree) Trace1 = QPushButton("Trace Cs->", self) Trace1.move(250, 80) Trace1.clicked.connect(self.Trace1) Trace2 = QPushButton("Trace Rb->", self) Trace2.move(420, 80) Trace2.clicked.connect(self.Trace2) CIPW = QPushButton("CIPW", self) CIPW.move(590, 80) CIPW.clicked.connect(self.CIPW) Ballard = QPushButton("Ballard", self) Ballard.move(590, 130) Ballard.clicked.connect(self.Ballard) MultiBallard = QPushButton("MultiBallard", self) MultiBallard.move(590, 180) MultiBallard.clicked.connect(self.MultiBallard) Qfl = QPushButton("Qfl", self) Qfl.move(250, 130) Qfl.clicked.connect(self.Qfl) Qmflt = QPushButton("Qmflt", self) Qmflt.move(80, 130) Qmflt.clicked.connect(self.Qmflt) QapfP = QPushButton("QapfP", self) QapfP.move(250, 180) QapfP.clicked.connect(self.QapfP) QapfV = QPushButton("QapfV", self) QapfV.move(80, 180) QapfV.clicked.connect(self.QapfV) Pearce = QPushButton("Pearce", self) Pearce.move(80, 360) Pearce.clicked.connect(self.Pearce) Harker = QPushButton("Harker", self) Harker.move(250, 360) Harker.clicked.connect(self.Harker) SingleRose = QPushButton("SingleRose", self) SingleRose.move(420, 360) SingleRose.clicked.connect(self.SingleRose) MultiRose = QPushButton("MultiRose", self) MultiRose.move(590, 360) MultiRose.clicked.connect(self.MultiRose) Wulf = QPushButton("Wulff", self) Wulf.move(420, 410) Wulf.clicked.connect(self.Wulf) Schmidt = QPushButton("Schmidt", self) Schmidt.move(590, 410) Schmidt.clicked.connect(self.Schmidt) self.lbl_hintX = QLabel(self) self.lbl_hintX.move(80, 250) self.lbl_hintX.setText("Input X for Harker:") self.lbl_hintX.adjustSize() self.lbl_hintY = QLabel(self) self.lbl_hintY.move(250, 250) self.lbl_hintY.setText("Input Y for Harker:") self.lbl_hintY.adjustSize() set_X = QLineEdit(self) set_X.move(80, 280) set_X.textChanged[str].connect(self.XChanged) set_Y = QLineEdit(self) set_Y.move(250, 280) set_Y.textChanged[str].connect(self.YChanged) self.lbl_X = QLabel(self) self.lbl_X.move(80, 330) self.lbl_Y = QLabel(self) self.lbl_Y.move(250, 330) self.lbl_SR = QLabel(self) self.lbl_SR.move(420, 330) self.lbl_MR = QLabel(self) self.lbl_MR.move(590, 330) self.lbl_hintSR = QLabel(self) self.lbl_hintSR.move(420, 250) self.lbl_hintSR.setText("Items for SingleRose:") self.lbl_hintSR.adjustSize() self.lbl_hintMR = QLabel(self) self.lbl_hintMR.move(590, 250) self.lbl_hintMR.setText("Item for MultiRose:") self.lbl_hintMR.adjustSize() set_SR = QLineEdit(self) set_SR.move(420, 280) set_SR.textChanged[str].connect(self.SRChanged) set_MR = QLineEdit(self) set_MR.move(590, 280) set_MR.textChanged[str].connect(self.MRChanged) self.lbl_SR = QLabel(self) self.lbl_SR.move(420, 330) self.lbl_MR = QLabel(self) self.lbl_MR.move(590, 330) self.statusBar() self.setGeometry(900, 600, 750, 500) self.setWindowTitle('GeoPython-GUI-Reluctantly') self.show() def XChanged(self, text): self.x = '' self.x = str(text) self.lbl_X.setText("X:" + text) self.lbl_X.adjustSize() def YChanged(self, text): self.y = [] self.y = str(text).split() self.lbl_Y.setText("Y:" + text) self.lbl_Y.adjustSize() def SRChanged(self, text): self.SR = '' self.SR = str(text) self.lbl_SR.setText("SR:" + text) self.lbl_SR.adjustSize() def MRChanged(self, text): self.MR = [] self.MR = str(text).split() self.lbl_MR.setText("MR:" + text) self.lbl_MR.adjustSize() def buttonClicked(self): sender = self.sender() self.statusBar().showMessage(sender.text() + ' was pressed') def showDialog(self): text, ok = QInputDialog.getText(self, 'Input Dialog', 'Enter Your X:') if ok: self.SetX.setText(str(text)) def Tas(self): a = 0 a = gp.Tas_Old() a.read() a = 0 def TasW(self): a = 0 a = gp.Tas() a.read() a = 0 def TasV(self): a = 0 a = gp.TasV() a.read() a = 0 def TasI(self): a = 0 a = gp.TasI() a.read() a = 0 def Ree(self): a = 0 a = gp.Ree() a.read() a = 0 def CIPW(self): a = 0 a = gp.CIPW() a.read() a = 0 def Trace1(self): a = 0 a = gp.Trace() a.read() a = 0 def Trace2(self): a = 0 a = gp.Trace2() a.read() a = 0 def Qfl(self): a = 0 a = gp.Qfl() a.read() a = 0 def Qmflt(self): a = 0 a = gp.Qmflt() a.read() a = 0 def QapfP(self): a = 0 gp.QapfP().read() a = 0 def QapfV(self): a = 0 a = gp.QapfV() a.read() a = 0 def Wulf(self): a = 0 a = gp.Polar() a.wulf() a = 0 def Schmidt(self): a = 0 a = gp.Polar() a.schmidt() a = 0 def SingleRose(self): a = 0 a = gp.Polar() a.singlerose(Name=self.SR.split()) a = 0 def MultiRose(self): a = 0 a = gp.Polar() a.multirose(Name=self.MR.split()[0]) a = 0 def Pearce(self): a = 0 a = gp.Pearce() a.read() a = 0 def Harker(self): print(self.x, "\t", self.y) a = 0 a = gp.Harker(x=self.x, y=self.y) a.read() a = 0 def Ballard(self): a = 0 a = gp.Ballard() a.read() a = 0 def MultiBallard(self): b = 0 b = gp.MultiBallard() b.read() b = 0
class Example(QWidget): def __init__(self): super().__init__() self.data = np.random.randint(1,10, (5,5)) print(self.data) print(os.path.dirname(os.path.abspath(__file__))) self.mysignal = Mysignal() self.lbl = QLabel("Ubuntu", self) self.combo = QComboBox(self) # data = {'file_paths': [r'e:\temp\README.txt', r'e:\профиль\t.hdf5', r'e:\профиль\тест.hdf5']} # self.combo.addItems(data['file_paths']) self.combo.setGeometry(0, 0, 200, 50) self.btn_save = QPushButton("Save", self) self.btn_save.setGeometry(0, 60, 60, 30) self.btn_save.clicked[bool].connect(self.save_file) btn_load = QPushButton("Load", self) btn_load.setGeometry(70, 60, 60, 30) # btn_load.clicked[bool].connect(self.load_file) btn_load.clicked.connect(self.btn_save.click) self.mysignal.mysignal.connect(self.save_file) # self.save_file() # self.combo.move(50, 50) self.lbl.setGeometry(80, 80, 50, 150) self.combo.activated[int].connect(self.selectionchange) self.setGeometry(300, 300, 500, 300) self.setWindowTitle('QComboBox') self.setWindowFlags(QtCore.Qt.Widget|QtCore.Qt.MSWindowsFixedSizeDialogHint) self.show() def get_save_filepath(self): description = 'Сохранить hdf5' default_path = os.path.dirname(os.path.abspath(__file__)) filter = "Таблицы hdf5 (*.hdf5)" path, _ = QFileDialog.getSaveFileName(self, description, default_path, filter) print(path) return path def save_file(self): path = self.get_save_filepath() self.combo.addItem(path) if path: Save()(self.data, filepath=path) def load_file(self): self.mysignal.mysignal.emit() def set_item(self, pressed): self.combo.addItem('f*****g code') def on_activated(self, text): self.lbl.setText(text + 'tail') self.lbl.adjustSize() def selectionchange(self, i): print("Items in the list are :") for count in range(self.combo.count()): print(self.combo.itemText(count)) print("Current index", i, "selection changed ", self.combo.currentText()) self.combo.addItem('DSL Linux')
class Realtime_PreView_Img(QScrollArea): def __init__(self, *args, **kwargs): QScrollArea.__init__(self, *args, **kwargs) self.View_Info = None self.View_Scale = 1 self.Add_Border = True self.Info_L_Most = 0 self.Info_T_Most = 0 self.Info_R_Most = 0 self.Info_B_Most = 0 self.draw_text = [] # {'text':#,'font':#,'rect':#} self.draw_marker = [] # {'rect':#} self.draw_Img = [] # {'rect':#} self.draw_rec = [] # {'rect':#} #self.Temp = QLabel(self) self.PreView_Img = None self.View = QLabel(self) self.View.setAlignment(Qt.AlignCenter) self.View.setScaledContents(True) # Preview自适应 #self.View.setMaximumWidth(700) self.setWidget(self.View) self.setAlignment(Qt.AlignCenter) self.View.setStyleSheet("border:2px solid red") def Load_info(self, Info): self.View_Info = Info self.Pre_set() self.Rearange() def Pre_set(self): if 'src_img' not in self.View_Info.keys(): self.View_Info['src_img'] = cv2.imread(self.View_Info['filename']) self.Gene_Font = QFont('Arial', C_Font_Size['Gene']) self.Marker_Font = QFont('Arial', C_Font_Size['Marker']) ###单独只有一项的时候默认将文字标签放在右边 if len(self.View_Info['crop']) > 0 and len( self.View_Info['markers']) > 0: if self.View_Info['crop'][0]['pos'][0] > self.View_Info['markers'][ 0]['pos'][0]: self.Postion_Type = 1 # Marker >> Strip >> Gene else: self.Postion_Type = 2 # Gene >> Strip >> Marker else: self.Postion_Type = 0 #默认情况统一放在右边 def Text_size(self, text, font): """ 获取 text设置为相应字体时候的大小 w,h=Text_size """ ### using QFontMetrics to get font size ff = QFontMetrics(font) text_w = ff.width(text) text_h = ff.height() return text_w, text_h def Rearange(self): self.draw_text = [] # {'text':#,'font':#,'rect':#} self.draw_marker = [] # {'rect':#} self.draw_Img = [] # {'rect':#} self.draw_rec = [] # {'rect':#} self.Spacer = ' ' self.crop_Center = 0 # 剪切中心 for m in self.View_Info['markers']: text = m['name'] text_w, text_h = self.Text_size(text + self.Spacer, self.Marker_Font) m_x, m_y, m_w, m_h = m['pos'] if self.Postion_Type == 1: # Marker >> Strip >> Gene text_pos = (m_x - text_w - 8, m_y - int( (text_h - m_h) / 2), text_w, text_h) align = Qt.AlignRight text = text + self.Spacer else: text_pos = (m_x + m_w + 8, m_y - int( (text_h - m_h) / 2), text_w, text_h) align = Qt.AlignLeft text = self.Spacer + text self.draw_text.append({ 'text': text, 'font': self.Marker_Font, 'rect': text_pos, 'align': align }) self.draw_marker.append({'rect': m['pos']}) for c in self.View_Info['crop']: text = c['name'] text_w, text_h = self.Text_size(text + self.Spacer, self.Gene_Font) m_x, m_y, m_w, m_h = c['pos'] if self.Postion_Type == 2: # Gene >> Strip >> Marker text_pos = (m_x - text_w - 8, m_y - int( (text_h - m_h) / 2), text_w, text_h) align = Qt.AlignRight text = text + self.Spacer else: text_pos = (m_x + m_w + 8, m_y - int( (text_h - m_h) / 2), text_w, text_h) align = Qt.AlignLeft text = self.Spacer + text self.draw_text.append({ 'text': text, 'font': self.Gene_Font, 'rect': text_pos, 'align': align }) self.draw_Img.append({'rect': c['pos']}) self.draw_rec.append( {'rect': (m_x - 2, m_y - 2, m_w + 3, m_h + 3)}) self.crop_Center = 2 * m_x + m_w l, t, r, b = [], [], [], [] for i in self.draw_marker + self.draw_rec + self.draw_text + self.draw_Img: l.append(i['rect'][0]) t.append(i['rect'][1]) r.append(i['rect'][0] + i['rect'][2]) b.append(i['rect'][1] + i['rect'][3]) self.Info_L_Most = min(l) - 5 if len(l) > 0 else 0 self.Info_T_Most = min(t) - 5 if len(t) > 0 else 0 self.Info_R_Most = max(r) if len(r) > 0 else 0 self.Info_B_Most = max(b) if len(b) > 0 else 0 # 调整L_Most 和R_Most 使其始终关于剪切图片中心对称 crop_Center = self.crop_Center if crop_Center: if self.Info_L_Most + self.Info_R_Most - crop_Center > 0: # 需要增加左侧 self.Info_L_Most -= self.Info_R_Most - crop_Center + self.Info_L_Most else: # 需要增加右侧 self.Info_R_Most += crop_Center - self.Info_L_Most - self.Info_R_Most self.dx = -self.Info_L_Most self.dy = -self.Info_T_Most def rect_fix(self, rect): x, y, w, h = rect return x + self.dx, y + self.dy, w, h def PreView(self): print("Patining") Img = QImage( QSize(self.Info_R_Most - self.Info_L_Most + 5, self.Info_B_Most - self.Info_T_Most + 5), QImage.Format_ARGB32) Img.fill(Qt.transparent) # Img.fill('white') pt = QPainter() pt.begin(Img) # 绘制文字 for i in self.draw_text: pt.setPen(QPen(QColor(0, 0, 0), 3)) pt.setFont(i['font']) x, y, w, h = self.rect_fix(i['rect']) pt.drawText(QRectF(x, y, w, h), i['align'], i['text']) #pt.drawRect(QRectF(x,y,w,h)) for r in self.draw_rec: x, y, w, h = self.rect_fix(r['rect']) pt.drawRect(QRectF(x, y, w, h)) for m in self.draw_marker: pt.setBrush(QColor(0, 0, 0)) x, y, w, h = self.rect_fix(m['rect']) pt.fillRect(x, y, w, h, QColor(0, 0, 0)) for p in self.draw_Img: im, _ = CV_Img_to_QImage(self.View_Info['src_img'], 1, self.View_Info['rotation'], self.View_Info['Flip_h'], self.View_Info['Flip_v']) x, y, w, h = p['rect'] im = im.copy(x, y, w, h) x, y, w, h = self.rect_fix(p['rect']) pt.drawPixmap(x, y, im) pt.end() return Img @pyqtSlot(list) def Sync_From(self, Imgb): Img = Imgb[0] info = Img.Pack_Info() self.Load_info(info) Img = self.PreView() t = QPixmap.fromImage(Img) #限定Preview地大小便于预览 if t.width() > self.width(): t = t.scaled(QSize(self.width(), self.height()), Qt.KeepAspectRatio) self.View.setPixmap(t) self.PreView_Img = Img self.View.adjustSize()
class AnotherWindow(QWidget): """Worker UI window class""" def __init__(self, rect, sensorPort): super().__init__() self.setGeometry(0, 0, 1000, 600) self.rect = rect self.sensorPort = sensorPort self.setWindowTitle("Qt live label demo") self.display_width = 440 self.display_height = 360 self.value = 80 #Create the label that holds the image self.image_label = QLabel(self) self.image_label.resize(self.display_width, self.display_height) self.image_label1 = QLabel(self) self.image_label1.resize(self.display_width, self.display_height) #Create a text label self.textLabel = QLabel('Webcam') self.adjustWin = None btn = QPushButton("Adjust", self) btn.move(300, 450) self.label = QLabel(str('Return'), self) self.label.move(300, 400) #Create label with box sizes self.labelSize = QLabel( str(' Size '), self) #self.labelSize.setStyleSheet("border: 1px solid black;") self.labelSize.adjustSize() self.labelSize.move(360, 400) #Create label for length meter self.labelLen = QLabel(str('Len'), self) self.labelLen.adjustSize() self.labelLen.move(360, 380) #Create button returning to adjust screen btn.clicked.connect(self.buttonClicked) self.error_flag = False #Сreate a vertical box layout and add the two labels vbox = QHBoxLayout() vbox.addWidget(self.image_label) self.image_label.move(0, 0) self.image_label1.move(450, 0) vbox.addWidget(self.image_label1) vbox.addWidget(self.textLabel) #Create slider widget sld = QSlider(Qt.Horizontal, self) sld.setRange(0, 255) sld.setFocusPolicy(Qt.NoFocus) sld.setPageStep(5) sld.valueChanged.connect(self.updateLabel) self.label = QLabel('0', self) self.label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter) self.label.setMinimumWidth(80) sld.move(400, 450) self.label.move(400, 500) vbox.addWidget(sld) vbox.addSpacing(15) vbox.addWidget(self.label) #Сreate the video capture thread self.thread = VideoThread(self.rect, self.sensorPort) #Сonnect its signal to the update_image slot self.thread.change_pixmap_signal.connect(self.update_image) self.thread.change_pixmap_signal1.connect(self.update_image1) self.thread.change_size_value.connect(self.update_size) self.thread.change_box_len_value.connect(self.update_len) self.thread.error_flag.connect(self.update_err_flag) try: self.thread.start() except: self.buttonClicked() def updateLabel(self, value): """Update current canny value method""" self.thread.sigs.change_canny_value.emit(value) self.label.setText(str(value)) def closeEvent(self, event): """Close window event""" self.thread.stop() event.accept() def buttonClicked(self): """Return to adjust event""" self.close() if self.adjustWin is None: self.winErr = Adjust() self.winErr.show() @pyqtSlot(bool) def update_err_flag(self, err_flag): """Slot updatiung error flag""" self.error_flag = err_flag if self.error_flag == True: self.buttonClicked() @pyqtSlot(str) def update_len(self, size_str): """Slot updating length meter label""" self.labelLen.adjustSize() self.labelLen.setText(str(size_str)) @pyqtSlot(str) def update_size(self, size_str): """Slot updating length meter label""" self.labelSize.adjustSize() self.labelSize.setText(str(size_str)) @pyqtSlot(np.ndarray) def update_image(self, cv_img): """Slot updating image """ qt_img = self.convert_cv_qt(cv_img) self.image_label.setPixmap(qt_img) @pyqtSlot(np.ndarray) def update_image1(self, cv_img): """Slot updating image """ qt_img = self.convert_cv_qt(cv_img) self.image_label1.setPixmap(qt_img) def convert_cv_qt(self, cv_img): """Converting np array image format to QPixmap format""" rgb_image = cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB) h, w, ch = rgb_image.shape bytes_per_line = ch * w convert_to_Qt_format = QtGui.QImage(rgb_image.data, w, h, bytes_per_line, QtGui.QImage.Format_RGB888) p = convert_to_Qt_format.scaled(self.display_width, self.display_height, Qt.KeepAspectRatio) return QPixmap.fromImage(p)
class CurrentMusicShort(QFrame): """用于显示当前歌曲的简单信息。""" def __init__(self, parent=None): super(CurrentMusicShort, self).__init__() self.parent = parent self.setObjectName('short') self.mousePos = None self.setLabels() self.setButtons() self.setLayouts() self.init() # 布局。 def setLabels(self): self.musicName = QLabel(self) self.musicName.adjustSize() self.musicAuthor = QLabel(self) def setButtons(self): # self.musicPic = QPushButton(self) self.musicPic = PicLabel('resource/no_music.png', 64, 64) self.musicPic.setObjectName("musicPic") self.musicPic.mousePressEvent = self.musicPicMousePressEvent self.musicPic.mouseReleaseEvent = self.musicPicMouseReleaseEvent def setLayouts(self): """布局。""" self.mainLayout = QHBoxLayout() self.mainLayout.setContentsMargins(0, 0, 0, 0) self.musicInfo = QVBoxLayout() self.mainLayout.setContentsMargins(0, 0, 0, 0) self.musicInfo.addWidget(self.musicName) self.musicInfo.addWidget(self.musicAuthor) self.mainLayout.addWidget(self.musicPic) self.mainLayout.addLayout(self.musicInfo) self.mainLayout.setStretch(0, 1) self.mainLayout.setStretch(1, 2) self.setLayout(self.mainLayout) # 功能。 def getDetailInfo(self): """点击后将自己隐藏并放大。""" return self.parent.getDetailInfo() self.hide() def init(self): """默认情况下的显示,包括音乐图片,音乐名和音乐作者。""" self.musicName.setText("Enjoy it") self.musicAuthor.setText("Enjoy it") # 事件。 def musicPicMousePressEvent(self, event): self.mousePos = QCursor.pos() def musicPicMouseReleaseEvent(self, evnet): if QCursor.pos() != self.mousePos: return else: self.getDetailInfo()
class Ui_Form(object): # Setup def setupUi(self, Form): # Links array self.links = [] Form.setObjectName("Form") # Window icon Form.setWindowIcon(QIcon("img/icon.ico")) # Unresizable Form.resize(397, 296) Form.setMaximumSize(397, 296) # Tab self.tabWidget = QTabWidget(Form) self.tabWidget.setGeometry(QRect(0, 0, 401, 301)) self.tabWidget.setStyleSheet("background-color: rgb(133, 181, 191);") self.tabWidget.setObjectName("tabWidget") self.tab_3 = QWidget() self.tab_3.setObjectName("tab_3") # Button to open github page self.githubButton = QPushButton(self.tab_3) self.githubButton.setGeometry(QRect(100, 0, 180, 120)) self.githubButton.setCursor(QCursor(Qt.OpenHandCursor)) self.githubButton.setIconSize(QSize(200, 120)) self.githubButton.setIcon(QIcon("img/GitHub.jpg")) self.githubButton.setObjectName("label") # Button to open telegram page self.telegramButton = QPushButton(self.tab_3) self.telegramButton.setGeometry(QRect(100, 140, 180, 120)) self.telegramButton.setCursor(QCursor(Qt.OpenHandCursor)) self.telegramButton.setText("") self.telegramButton.setIcon(QIcon("img/Telegram.jpg")) self.telegramButton.setIconSize(QSize(210, 120)) self.telegramButton.setObjectName("label_2") self.tabWidget.addTab(self.tab_3, "") self.tab_2 = QWidget() self.tab_2.setObjectName("tab_2") self.tab_1 = QWidget() self.tab_1.setObjectName("tab_1") # Text next to url entry self.urlText = QLabel(self.tab_2) self.urlText.setGeometry(QRect(10, 10, 111, 31)) font = QFont() font.setFamily("Berlin Sans FB") font.setPointSize(15) font.setBold(True) font.setWeight(75) self.urlText.setFont(font) self.urlText.setObjectName("urlText") # Text entry to get url self.url = QPlainTextEdit(self.tab_2) self.url.setGeometry(QRect(150, 10, 181, 41)) font = QFont() font.setFamily("Berlin Sans FB") font.setPointSize(15) font.setBold(False) font.setWeight(50) self.url.setFont(font) self.url.viewport().setProperty("cursor", QCursor(Qt.IBeamCursor)) self.url.setObjectName("url") # Text next to filter key text entry self.filterText = QLabel(self.tab_2) self.filterText.setGeometry(QRect(10, 50, 121, 61)) font = QFont() font.setFamily("Berlin Sans FB") font.setPointSize(15) font.setBold(True) font.setWeight(75) self.filterText.setFont(font) self.filterText.setWordWrap(True) self.filterText.setObjectName("filterText") # Filter key entry self.contain = QPlainTextEdit(self.tab_2) self.contain.setGeometry(QRect(150, 50, 181, 61)) font = QFont() font.setFamily("Berlin Sans FB") font.setPointSize(15) self.contain.setFont(font) self.contain.viewport().setProperty("cursor", QCursor(Qt.IBeamCursor)) self.contain.setObjectName("contain") # Button to submit url self.urlButton = QPushButton(self.tab_2) self.urlButton.setGeometry(QRect(340, 10, 41, 41)) font = QFont() font.setFamily("Berlin Sans FB") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.urlButton.setFont(font) self.urlButton.setCursor(QCursor(Qt.OpenHandCursor)) self.urlButton.setText("OK") self.urlButton.setObjectName("urlButton") # Button to submit filter key self.filterButton = QPushButton(self.tab_2) self.filterButton.setEnabled(False) self.filterButton.setGeometry(QRect(340, 60, 41, 41)) font = QFont() font.setFamily("Berlin Sans FB") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.filterButton.setFont(font) self.filterButton.setCursor(QCursor(Qt.OpenHandCursor)) self.filterButton.setText("OK") self.filterButton.setObjectName("filterButton") # "RESULTS" label self.resultText = QLabel(self.tab_2) self.resultText.setGeometry(QRect(10, 120, 50, 50)) font.setBold(True) font.setPointSize(15) self.resultText.setFont(font) self.resultText.setText("RESULTS") self.resultText.adjustSize() self.resultText.setObjectName("resultText") font = QFont() font.setFamily("Berlin Sans FB") font.setPointSize(15) font.setBold(True) font.setWeight(75) # Creating scroll label self.label = ScrollLabel(self.tab_2) self.label.setGeometry(10, 150, 300, 100) # Button to open url self.pushButton = QPushButton(self.tab_2) self.pushButton.setEnabled(False) self.pushButton.setGeometry(QRect(100, 125, 70, 20)) font = QFont() font.setFamily("Berlin Sans FB") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.pushButton.setFont(font) self.pushButton.setCursor(QCursor(Qt.OpenHandCursor)) self.pushButton.setObjectName("pushButton") # Title of help text self.help_title_label = QLabel(self.tab_1) self.help_title_label.setText("HOW TO USE ?") self.help_title_label.move(10, 10) self.help_title_label.setFont(font) self.help_label = QLabel(self.tab_1) font.setBold(False) font.setPointSize(12) # Help text helpText = "OPEN LINK COLLECTOR TAB AND WRITE THE URL \nTHAT YOU WANT FIND LINKS. THEN CLICK OK BUTTON.\n\nTO FILTER LINKS, WRITE WHICH SHOULD LINK \nCONTAIN TO THE TEXT ENTRY.\n\nTO OPEN A URL WRITE WRITE INDEX OF URL TO \nPOP UP DIALOG AND CLICK OK." # Help text label self.help_label.setFont(font) self.help_label.move(10, 30) self.help_label.setText(helpText) self.help_label.setWordWrap(True) # Add tabs self.tabWidget.addTab(self.tab_1, "") self.tabWidget.addTab(self.tab_2, "") self.tabWidget.addTab(self.tab_3, "") self.retranslateUi(Form) #Set current tab self.tabWidget.setCurrentIndex(0) QMetaObject.connectSlotsByName(Form) # Method to open github page def github(self): open("https://github.com/SukruGokk") # Method to open telegram page def telegram(self): open("https://t.me/SukruGokk") # Method for get urls def connect(self): # Get link from user with input url = self.url.document().toPlainText() # Try to connect try: # Connect r = get(url) # Parse page's codes soup = BS(r.content, "lxml") # Get links from site content for link in soup.findAll('a'): # If it doesnt contains http, dont but if it contains append if str(link.get('href')).find("http") == -1: pass else: self.links.append(link.get('href')) # Enable button to submit filter key self.filterButton.setEnabled(True) # String of links self.strLinks = "" # Add list's elements to string num = 1 for i in self.links: self.strLinks += str(num) self.strLinks += " " self.strLinks += i self.strLinks += '\n' num += 1 # Display urls self.label.setText(self.strLinks) self.filteredLinks = self.links # Enable open link button self.pushButton.setEnabled(True) # If url if invalid except: # Show error message msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("INVALID URL") msg.setWindowTitle("ERROR") msg.setFont(QFont("Berlin Sans FB", 20, 17)) msg.exec_() # Filter the links according to filter key def filterLinks(self): self.filterKey = self.contain.document().toPlainText() self.filteredLinks = [] for i in self.links: if i.find(self.filterKey) != -1: self.filteredLinks.append(i) num = 1 self.strLinks = "" for i in self.filteredLinks: self.strLinks += str(num) self.strLinks += " " self.strLinks += i self.strLinks += '\n' num += 1 self.label.setText(self.strLinks) # Open selected link def openLink(self): text, okPressed = QInputDialog.getText(self.tab_2, "NUMBER OF URL", "NUMBER: ", QLineEdit.Normal, "") # Open url try: if okPressed: open(self.filteredLinks[int(text)-1]) # If index is invalid except: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("INVALID") msg.setFont(QFont("Berlin Sans FB", 20, 17)) msg.setWindowTitle("INVALID") msg.exec_() # Retranslate method def retranslateUi(self, Form): _translate = QCoreApplication.translate # Set title Form.setWindowTitle("LINK COLLECTOR") # Set tab text self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_1), _translate("Form", "HELP")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("Form", "LINK COLLECTOR")) self.urlText.setText(_translate("Form", "WRITE URL")) self.filterText.setText(_translate("Form", "What should link contain")) self.pushButton.setText(_translate("Form", "OPEN LINK")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("Form", "DEVELOPER")) self.url.document().setPlainText("https://") # Onlick events self.urlButton.clicked.connect(self.connect) self.filterButton.clicked.connect(self.filterLinks) self.pushButton.clicked.connect(self.openLink) self.githubButton.clicked.connect(self.github) self.telegramButton.clicked.connect(self.telegram)
def initUI(self): count = 1 count2 = 1 ID = [] Name = [] # Generating the list of all items self.cursor.execute("""SELECT * FROM Item""") items = self.cursor.fetchall() # Getting the ID and name of each hero self.cursor.execute("""SELECT hero_number, hero_name FROM Hero""") for i in self.cursor.fetchall(): ID.append(i[0]) Name.append(i[1]) idWithKeys = dict(zip(ID, Name)) # Generating the headers New_item = QLabel("Unequipped items:", self) New_item.move(350, 30 * count2) New_item.setFont(QFont('ComicSans', 14)) New_item.adjustSize() count2 += 1 New_item = QLabel("Equipped items:", self) New_item.move(20, 30 * count) New_item.setFont(QFont('ComicSans', 14)) New_item.adjustSize() count += 1 # Generating the labels for each item for item in items: # If someone carrying the item if item[6] is not None: # Item name New_item = QLabel(item[1], self) New_item.move(20, 30 * count) New_item.setFont(QFont('SansSerif', 13)) New_item.adjustSize() count += 1 # Item description New_item = QLabel(item[2], self) New_item.move(20, 30 * count) New_item.adjustSize() count += 1 # Item stats New_item = QLabel( "STR = {}, AGI = {}, INT = {}".format( item[3], item[4], item[5]), self) New_item.move(20, 30 * count) New_item.adjustSize() count += 1 # The name of the holder New_item = QLabel( "Right now {} is using this item".format( idWithKeys[item[6]]), self) New_item.move(20, 30 * count) New_item.adjustSize() count += 1 # If no one is carrying the item if item[6] is None: # Item name New_item = QLabel(item[1], self) New_item.move(350, 30 * count2) New_item.setFont(QFont('SansSerif', 13)) New_item.adjustSize() count2 += 1 # Item description New_item = QLabel(item[2], self) New_item.move(350, 30 * count2) New_item.adjustSize() count2 += 1 # Item stats New_item = QLabel( "STR = {}, AGI = {}, INT = {}".format( item[3], item[4], item[5]), self) New_item.move(350, 30 * count2) New_item.adjustSize() count2 += 1 # The name of the holder New_item = QLabel("No one is using this item", self) New_item.move(350, 30 * count2) New_item.adjustSize() count2 += 1 self.setGeometry(300, 300, 600, 800) self.setWindowTitle('Items Database') self.show() self.connection.close()
class MainForm(QWidget): def getx(self): return self.__addwin def setx(self, value): self.__addwin = value def delx(self): del self.__addwin addwin = property(getx, setx, delx, "Свойство 'addwin'.") def __init__(self): super(MainForm, self).__init__() self.initUI() def initUI(self): addtextdocument = QPushButton("Добавить текстовый документ") addtextdocument.clicked.connect(self.ATDDialog) but_subject_area = QPushButton("Добавить предметную область") but_subject_area.setEnabled(False) self.but_extracting_keywords = QPushButton("Извлечь ключевые слова") self.but_extracting_keywords.setEnabled(False) self.but_extracting_keywords.clicked.connect(self.RunExtractingKey) but_add_dictionary = QPushButton("Добавить в словарь") but_add_dictionary.setEnabled(False) but_save = QPushButton("Сохранить результат") but_save.setEnabled(False) self.but_algorithms_estimation = QPushButton("Оценка алгоритма") # self.but_algorithms_estimation.setEnabled(False) self.but_algorithms_estimation.clicked.connect(self.RunEstimation) self.address = QLabel("Необходимо выборать файл с расширением '.txt'") leb1 = QLabel("Предметная область") leb2 = QLabel("Размер выборки ключевых слов") results_extraction = QLabel("Полученные ключевые слова:") self.comb_subject_area = QComboBox(self) self.comb_subject_area.setEditable(False) self.comb_subject_area.addItem( "50.41.17 Системное программное обеспечение") self.sample_size = QSpinBox(self, minimum=0, maximum=20) self.sample_size.setEnabled(False) self.sample_size.valueChanged.connect(self.CheckExtract) self.keywords_line = QListWidget() grid = QGridLayout() grid.setSpacing(10) grid.addWidget(addtextdocument, 1, 0) grid.addWidget( self.address, 1, 1, 1, 1, ) grid.addWidget(leb1, 2, 0) grid.addWidget(self.comb_subject_area, 2, 1) grid.addWidget(but_subject_area, 2, 2) grid.addWidget(leb2, 3, 0) grid.addWidget(self.sample_size, 3, 1) grid.addWidget(results_extraction, 4, 0) grid.addWidget(self.keywords_line, 5, 0, 5, 2) grid.addWidget(self.but_extracting_keywords, 5, 2) grid.addWidget(but_add_dictionary, 6, 2) grid.addWidget(but_save, 10, 0) grid.addWidget(self.but_algorithms_estimation, 10, 1) self.setLayout(grid) self.setGeometry(300, 300, 900, 600) self.setWindowTitle('Извлечение ключевых слов') self.show() def ATDDialog(self): self.address_text = QFileDialog.getOpenFileName( self, 'Выберите документ', '', 'Text Files (*.txt)') self.address.setText('Загруженный файл: ' + self.address_text[0]) self.address.adjustSize() self.sample_size.setEnabled(True) def RunEstimation(self): self.addwin = AlgorithmsEstimationForm() def CheckExtract(self): if self.sample_size.value() != 0: self.but_extracting_keywords.setEnabled(True) else: self.but_extracting_keywords.setEnabled(False) def RunExtractingKey(self): self.but_extracting_keywords.setEnabled(False) self.keywords_line.clear() self.keyword = PreliminaryProcessing(self.address_text[0]) print('End PreliminaryProcessing') self.keyword = DefinitionCharacteristics(self.keyword.fin_dict_Cand) print('End DefinitionCharacteristics') self.keyword = Postprocessing(self.keyword.candidate_words, int(self.sample_size.value())) print('End Postprocessing') for n in self.keyword.fin_KeyWords: self.keywords_line.addItem(n) self.but_extracting_keywords.setEnabled(True) self.but_algorithms_estimation.setEnabled(True) def closeEvent(self, event): reply = QMessageBox.question(self, 'Выход', 'Вы точно хотите выйти?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: event.accept() else: event.ignore()
class MainUI(QWidget): def __init__(self): super().__init__() self.init_ui() # 窗体GUI部分 def init_ui(self): # 设置窗体大小 self.setGeometry(500, 200, 350, 200) # 设置固定大小 self.setFixedSize(520, 370) self.setWindowTitle('pdf拆分') # 进度条 self.pbar = QProgressBar(self) # 进图条位置及大小 self.pbar.setGeometry(20, 120, 450, 20) # todo 按钮 # 选择XML文件按钮 self.btn_select_file1 = QPushButton('选择xml文件', self) self.btn_select_file1.move(20, 190) self.btn_select_file1.setFixedSize(125, 30) self.btn_select_file1.clicked.connect(self.file_dialog1) # 选择文件按钮 self.btn_select_file = QPushButton('选择pdf文件', self) self.btn_select_file.move(20, 230) self.btn_select_file.setFixedSize(125, 30) self.btn_select_file.clicked.connect(self.file_dialog) # 输出文件按钮 self.btn_output_path = QPushButton('选择输出文件夹', self) self.btn_output_path.move(20, 270) self.btn_output_path.setFixedSize(125, 30) self.btn_output_path.clicked.connect(self.output_dialog) # 开始按钮 self.btn = QPushButton('开始', self) # 创建按钮并移动 self.btn.move(150, 310) self.btn.setFixedSize(200, 40) # 点击按钮,连接事件函数 self.btn.clicked.connect(self.btn_action) # todo 标签 # xml文件路径标签 self.lab_select_path1 = QLabel('xml文件路径', self) self.lab_select_path1.move(150, 190) self.lab_select_path1.setFixedSize(320, 30) self.lab_select_path1.setFrameShape(QFrame.Box) self.lab_select_path1.setFrameShadow(QFrame.Raised) # 文件路径标签 self.lab_select_path = QLabel('文件路径', self) self.lab_select_path.move(150, 230) self.lab_select_path.setFixedSize(320, 30) self.lab_select_path.setFrameShape(QFrame.Box) self.lab_select_path.setFrameShadow(QFrame.Raised) # 输出标签 self.lab_output_path = QLabel('文件路径', self) self.lab_output_path.move(150, 270) self.lab_output_path.setFixedSize(320, 30) self.lab_output_path.setFrameShape(QFrame.Box) self.lab_output_path.setFrameShadow(QFrame.Raised) # 说明标签 content = '说明:\n 选择需要拆分的pdf,选择输出结果文件夹。\n pdf拆分按照填写的开始页码和截止页码的区间来拆分,只拆分当前目录内容。' self.description_lab = QLabel(content, self) self.description_lab.move(20, 10) self.description_lab.setFixedSize(450, 100) self.description_lab.setAlignment(Qt.AlignTop) self.description_lab.setFrameShape(QFrame.Box) self.description_lab.setFrameShadow(QFrame.Raised) # 自动换行 # self.description_lab.adjustSize() self.description_lab.setWordWrap(True) # # 提取开始页码 self.btn_select_file2 = QPushButton('提取开始页码', self) self.btn_select_file2.move(20, 150) self.btn_select_file2.setFixedSize(100, 30) int_validato = QIntValidator(50, 100, self) # 实例化整型验证器,并设置范围为50-100 self.int_le = QLineEdit(self) # 整型文本框 self.int_le.setValidator(int_validato) # 设置验证 self.int_le.setFixedSize(100, 30) self.int_le.move(120, 150) # 截止页码 self.btn_select_file1 = QPushButton('提取截止页码', self) self.btn_select_file1.move(260, 150) self.btn_select_file1.setFixedSize(100, 30) int_validato1 = QIntValidator(50, 100, self) # 实例化整型验证器,并设置范围为50-100 self.int_le1 = QLineEdit(self) # 整型文本框 self.int_le1.setValidator(int_validato1) # 设置验证 self.int_le1.setFixedSize(100, 30) self.int_le1.move(360, 150) self.step = 0 # 显示 self.show() # 按钮点击 def btn_action(self): if self.btn.text() == '完成': self.close() else: file_path = '{}'.format(self.lab_select_path.text()) xml_file_path = '{}'.format(self.lab_select_path1.text()) output_path = '{}'.format(self.lab_output_path.text()) start_pageno = self.int_le.text() end_pageno = self.int_le1.text() if self.btn.text() == '开始': if not os.path.exists(file_path): QMessageBox.warning(self, '', '请选择路径', QMessageBox.Yes) elif not os.path.exists(output_path): QMessageBox.warning(self, '', '请选择输出路径', QMessageBox.Yes) elif start_pageno == '': QMessageBox.warning(self, '', '请输入开始页码', QMessageBox.Yes) elif end_pageno == '': QMessageBox.warning(self, '', '请输入截止页码', QMessageBox.Yes) else: self.btn.setText('程序进行中') # self.run() self.downloadThread = downloadThread( file_path, output_path, start_pageno, end_pageno) self.downloadThread.download_proess_signal.connect( self.set_progerss_bar) self.downloadThread.start() # 选择输入文件路径 def file_dialog(self): # './'表示当前路径 # path = QFileDialog.getExistingDirectory(self, '选取文件', './', 'pdf文件(*.pdf)') path = QFileDialog.getOpenFileName(self, '选取文件', './', 'pdf文件(*.pdf)') print(path) # 标签框显示文本路径 self.lab_select_path.setText(path[0]) # 自动调整标签框大小 self.lab_select_path.adjustSize() # 选择输入xml文件路径 def file_dialog1(self): # './'表示当前路径 # path = QFileDialog.getExistingDirectory(self, '选取文件', './', 'pdf文件(*.pdf)') path = QFileDialog.getOpenFileName(self, '选取文件', './', 'xml文件(*.xml)') print(path) # 标签框显示文本路径 self.lab_select_path1.setText(path[0]) # 自动调整标签框大小 self.lab_select_path1.adjustSize() # 选择输出路径 def output_dialog(self): path = QFileDialog.getExistingDirectory(self, '选取文件夹', './') # 标签框显示文本路径 self.lab_output_path.setText(path) # 自动调整标签框大小 self.lab_output_path.adjustSize() def set_progerss_bar(self, num): ''' 设置进图条函数 :param num: 进度条进度(整数) :return: ''' self.step = num self.pbar.setValue(self.step) if num == 100: self.btn.setText('完成') QMessageBox.information(self, "提示", "提取完成!") return def pdf_splitter(path): """ pdf按照页码拆分 :param path: :return: """ fname = os.path.splitext(os.path.basename(path))[0] pdf = PdfFileReader(path) for page in range(pdf.getNumPages()): pdf_writer = PdfFileWriter() pdf_writer.addPage(pdf.getPage(page)) output_filename = '{}_page_{}.pdf'.format(fname, page + 1) with open(output_filename, 'wb') as out: pdf_writer.write(out) print('created:{}'.format(output_filename))
class NamekoManWidget(QWidget): RPC = "rpc" def __init__(self): super().__init__() self.broker = const.BROKER self.brokerEdit = QLineEdit(self.broker) self.brokerEdit.setPlaceholderText("Input mq broker, for example: {}".format(const.BROKER)) self.timeout = const.TIMEOUT self.timeoutEdit = QLineEdit(str(self.timeout)) self.timeoutEdit.setPlaceholderText("Input timeout") self.timeoutEdit.setMaximumWidth(100) self.timeoutEdit.setValidator(QIntValidator(1, 1000)) self.sendButton = QPushButton(const.SEND_BUTTON_SEND_TEXT) self.serviceEdit = QLineEdit() self.serviceEdit.setFocusPolicy(QtCoreQt.NoFocus) self.serviceEdit.setPlaceholderText("Input service name, for example: {}".format(const.SERVICE_INPUT)) self.methodEdit = QLineEdit() self.methodEdit.setFocusPolicy(QtCoreQt.NoFocus) self.methodEdit.setMinimumWidth(400) self.methodEdit.setPlaceholderText("Input method name, for example: {}".format(const.METHOD_INPUT)) # 初始化输出日志组件 self.logTextBox = QTextEditLogger(self) self.logTextBox.widget.setMinimumHeight(150) self.logTextBox.widget.setMaximumHeight(300) self.logTextBox.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")) logging.getLogger().addHandler(self.logTextBox) logging.getLogger().setLevel(logging.DEBUG) # 初始化代码编辑控件 lexer = QsciLexerJSON() lexer.setHighlightComments(False) lexer.setHighlightEscapeSequences(False) self.paramsEdit = NamekoManQsciScintilla() self.paramsEdit.setLexer(lexer) self.paramsEdit.setUtf8(True) self.paramsEdit.setMarginLineNumbers(0, True) self.paramsEdit.setAutoIndent(True) self.paramsEdit.setTabWidth(4) self.paramsEdit.setFolding(QsciScintilla.BoxedTreeFoldStyle) self.paramsEdit.setFoldMarginColors(QtCoreQt.gray, QtCoreQt.lightGray) self.paramsEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.paramsEdit.setIndentationGuides(QsciScintilla.SC_IV_LOOKBOTH) # 初始化结果显示控件,支持滚动 self.scrollArea = QScrollArea() self.scrollArea.setWidgetResizable(True) self.resultLabel = QLabel("") self.resultLabel.setAlignment(QtCoreQt.AlignCenter) self.resultLabel.adjustSize() self.resultLabel.setWordWrap(True) self.resultLabel.setAlignment(QtCoreQt.AlignLeft) self.resultLabel.setTextInteractionFlags(QtCoreQt.TextSelectableByMouse) self.resultLabel.setText(const.README) self.scrollArea.setWidget(self.resultLabel) self.scrollArea.setMinimumSize(500, 600) # 初始化文件夹树 self.folderBar = FolderWidget() # 使用网格布局进行布局 self.layout = QGridLayout() self.layout.setContentsMargins(10, 0, 10, 0) self.layout.addWidget(self.folderBar, 0, 0, 25, 1) self.layout.addWidget(self.brokerEdit, 0, 1, 1, 1) self.layout.addWidget(self.timeoutEdit, 0, 2, 1, 1) self.layout.addWidget(self.serviceEdit, 1, 1, 1, 2) self.layout.addWidget(self.methodEdit, 2, 1, 1, 2) self.layout.addWidget(self.paramsEdit, 3, 1, 22, 2) self.layout.addWidget(self.sendButton, 0, 3, 1, 1) self.layout.addWidget(self.scrollArea, 1, 3, 24, 1) self.layout.addWidget(self.logTextBox.widget, 25, 0, 1, 4) self.setLayout(self.layout) self.sendButton.clicked.connect(self.onSendRpc) self.folderBar.clickNodeSingal.connect(self.onClickedNode) # 初始化nameko client self.initNameko() self.rpcThread = None self.nodeInfo = None def showResult(self, result: str): # 为了显示居中,用2个空格替换1个空格 self.resultLabel.setText(result.replace(" ", " ")) self.resultLabel.repaint() def getBrokerInput(self): return self.brokerEdit.text() def getTimeoutInput(self): timeout = self.timeoutEdit.text() try: return int(timeout) except Exception as e: logging.exception(e) return const.TIMEOUT def hasNamekoClient(self): return hasattr(self, self.RPC) def setNamekoClient(self): """ 更新配置,再设置一个新的rpc客户端 """ setup_config(None, define=getAMQPConfig(self.broker)) client = ClusterRpcClient(timeout=self.getTimeoutInput()) setattr(self, self.RPC, client.start()) logging.info( "Set new nameko, broker:{}, timeout:{}".format(self.getBrokerInput(), self.getTimeoutInput()) ) def initNameko(self): """ 如果没有构建好rpc客户端,新建一个,如果已经构建好删除再使用新的配置新建 """ broker = self.getBrokerInput() timeout = self.getTimeoutInput() try: if not self.hasNamekoClient(): self.broker = broker self.setNamekoClient() else: if broker != self.broker or timeout != self.timeout: self.broker = broker self.timeout = timeout delattr(self, self.RPC) self.setNamekoClient() except Exception as e: self.showResult(utils.errorToJsonStr(repr(e))) logging.exception(e) def lockSendButton(self): self.sendButton.setDisabled(True) self.sendButton.setText(const.SEND_BUTTON_WAIT_TEXT) self.sendButton.repaint() def unlockSendButton(self): self.sendButton.setDisabled(False) self.sendButton.setText(const.SEND_BUTTON_SEND_TEXT) self.sendButton.repaint() def onClickedNode(self, info): """ 显示鼠标选择节点数据 """ self.serviceEdit.setText(info.get(const.NODE_SERVICE, "")) self.methodEdit.setText(info.get(const.NODE_METHOD, "")) params = info.get(const.PARAMS, {}) result = info.get(const.RESULT, {}) if params is not None: self.paramsEdit.setText(utils.objectToJsonStr(params)) if result is not None: self.showResult(utils.objectToJsonStr(result)) self.nodeInfo = info def onSendRpc(self): self.initNameko() if not self.hasNamekoClient(): self.showResult(utils.errorToJsonStr("Can't connect to mq, please check mq or broker!")) return node = self.folderBar.getCurrentClickedNode() if not node or node.getType() != const.NODE_METHOD: alert("Please choose one method!") return service, method, params = self.serviceEdit.text(), self.methodEdit.text(), self.paramsEdit.text() try: params = json.loads(params) self.lockSendButton() self.rpcThread = SendRpcThread( getattr(self, self.RPC), self.nodeInfo.get(const.NODE_PROJECT, ""), service, self.nodeInfo.get(const.NODE_MODULE, ""), method, params ) self.rpcThread.finishSignal.connect(self.onSendRpcFinished) self.rpcThread.start() except Exception as e: self.showResult(utils.errorToJsonStr(repr(e))) node.updateParams(params) def onSendRpcFinished(self, data: str): data = json.loads(data) result = utils.objectToJsonStr(data["result"]) if len(result) > const.MAX_LENGTH: result = result[:const.MAX_LENGTH] result += "...... Sorry, the result is too long. Please check the log for whole result." self.showResult(result) self.unlockSendButton() if "error" not in result.lower() and len(result) < const.MAX_LENGTH: storage.updateResut( data[const.NODE_PROJECT], data[const.NODE_SERVICE], data[const.NODE_MODULE], data[const.NODE_METHOD], data["result"] )
class ImageViewer(QMainWindow): def __init__(self): super(ImageViewer, self).__init__() self.printer = QPrinter() self.scaleFactor = 0.0 self.directory="" self.imageLabel = QLabel() self.imageLabel.setBackgroundRole(QPalette.Base) self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.imageLabel.setScaledContents(True) self.scrollArea = QScrollArea() self.scrollArea.setBackgroundRole(QPalette.Dark) self.scrollArea.setWidget(self.imageLabel) self.setCentralWidget(self.scrollArea) self.createActions() self.createMenus() self.setWindowTitle("IOA Image Viewer") self.resize(800, 600) def openImg(self,fileName): self.imageLabel = QLabel() self.imageLabel.setBackgroundRole(QPalette.Base) self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.imageLabel.setScaledContents(True) image = QImage(fileName) self.imageLabel.setPixmap(QPixmap.fromImage(image)) self.scaleFactor = 1.0 self.printAct.setEnabled(True) self.fitToWindowAct.setEnabled(True) self.updateActions() def open(self): fileName, _ = QFileDialog.getOpenFileName(self, "Open File", QDir.currentPath()) self.directory=fileName print(fileName) if fileName: image = QImage(fileName) if image.isNull(): QMessageBox.information(self, "Image Viewer", "Cannot load %s." % fileName) return self.imageLabel.setPixmap(QPixmap.fromImage(image)) self.scaleFactor = 1.0 self.printAct.setEnabled(True) self.fitToWindowAct.setEnabled(True) self.updateActions() if not self.fitToWindowAct.isChecked(): self.imageLabel.adjustSize() def print_(self): dialog = QPrintDialog(self.printer, self) if dialog.exec_(): painter = QPainter(self.printer) rect = painter.viewport() size = self.imageLabel.pixmap().size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(self.imageLabel.pixmap().rect()) painter.drawPixmap(0, 0, self.imageLabel.pixmap()) def zoomIn(self): self.scaleImage(1.25) def zoomOut(self): self.scaleImage(0.8) def normalSize(self): self.imageLabel.adjustSize() self.scaleFactor = 1.0 def fitToWindow(self): fitToWindow = self.fitToWindowAct.isChecked() self.scrollArea.setWidgetResizable(fitToWindow) if not fitToWindow: self.normalSize() self.updateActions() def faceDetect(self): try: face_cascade = cv2.CascadeClassifier(r"FaceRcognition-master\haarcascade_frontalface_default.xml") img = cv2.imread(self.directory) grey_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(grey_img, scaleFactor=1.05, minNeighbors=5) c=0 #crop=[] #print(type(faces)) #print(faces) for x, y, w, h in faces: #crop.append(img[y:y+h,x:x+w]) #crimg=cv2.circle(img, (x+int(h/2), y+int(w/2)), int(h/2), (0, 255, 0), 3) img = cv2.rectangle(img, (x,y), (x+w, y+w), (0,255,0), 2) c=c+1 #a=0 #print(c) # for cimg in crop: # name="face detected image"+str(c) # cv2.imshow(name, cimg) # c+=1 #self.imageLabel.setPixmap(img) #print(QDir.currentPath) cv2.imwrite("Detected.jpg",img) #print(os.getcwd()) cdr=str(os.getcwd())+'\Detected.jpg' #pic = cdr[:-2]+"Detected.jpg'" image = QImage(cdr) if image.isNull(): QMessageBox.information(self, "IOA Image Viewer", "Cannot load %s." % cdr) return self.imageLabel.setPixmap(QPixmap.fromImage(image)) # cv2.imshow("face detected image", img) # cv2.waitKey(0) # cv2.destroyAllWindows() except: pass def imgResize(self): try: img = cv2.imread(self.directory,1) oheight, owidth = img.shape[0:2] iheight, hokPressed = QInputDialog.getInt(self, "Get Height","Height :", 0, 0, int(oheight), 1) iwidth , okPressed = QInputDialog.getInt(self, "Get Width","Width :", 0, 0, int(owidth), 1) resizedImg = cv2.resize(img,(int(iwidth),int(iheight))) print(iheight) print(iwidth) cv2.imshow("Resized.jpg",resizedImg) cv2.imwrite("Resized.jpg",resizedImg) cdr=str(QDir.currentPath())+'/Resized.jpg' print(cdr) self.openImg(cdr) # cdr=str(os.getcwd())+'\\Resized.jpg' # Rimage = QImage(cdr) # if Rimage.isNull(): # QMessageBox.information(self, "IOA Image Viewer", # "Cannot load %s." % cdr) # return # self.imageLabel.setPixmap(QPixmap.fromImage(Rimage)) # self.scaleFactor = 1.0 # self.imageLabel.setScaledContents(True) except: pass # scale_percent = 100 # percent of original size # width = int(img.shape[1] * scale_percent / 100) # height = int(img.shape[0] * scale_percent / 100) # dim = (width, height) # resized = cv2.resize(img, dim) def imgRotate(self): try: colorImage = Image.open(self.directory) transposed = colorImage.transpose(Image.ROTATE_90) transposed = transposed.save('Rotated.jpg') cdr=str(os.getcwd())+'\\Rotated.jpg' image = QImage(cdr) if image.isNull(): QMessageBox.information(self, "IOA Image Viewer", "Cannot load %s." % cdr) return self.imageLabel.setPixmap(QPixmap.fromImage(image)) except: pass def imgCropFace(self): try: img = cv2.imread(self.directory) face_cascade = cv2.CascadeClassifier(r"FaceRcognition-master\haarcascade_frontalface_default.xml") grey_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(grey_img, scaleFactor=1.05, minNeighbors=5) c=0 for x,y,w,h in faces: img = cv2.rectangle(img,(x,y),(x+w, y+w),(0,255,0),1) cropped = img[y:y+h, x:x+w] cv2.imwrite("Rotated.jpg",cropped) cdr=str(os.getcwd())+'\\Rotated.jpg' image = QImage(cdr) if image.isNull(): QMessageBox.information(self, "IOA Image Viewer", "Cannot load %s." % cdr) return self.imageLabel.setPixmap(QPixmap.fromImage(image)) except: pass # def imgBlur(self): # img = cv2.imread(self.directory) # blur_image = cv2.GaussianBlur(img, (7,7), 0) #scale 1,2,3,4,5 # def imgEdge(self): # edge_img = cv2.Canny(img,100,200) #def imgDenoise(self): # result = cv2.fastNlMeansDenoisingColored(img,None,20,10,7,21) def about(self): QMessageBox.about(self, "About Image Viewer", "<p>The <b>Image Viewer</b> example shows how to combine " "QLabel and QScrollArea to display an image. QLabel is " "typically used for displaying text, but it can also display " "an image. QScrollArea provides a scrolling view around " "another widget. If the child widget exceeds the size of the " "frame, QScrollArea automatically provides scroll bars.</p>" "<p>The example demonstrates how QLabel's ability to scale " "its contents (QLabel.scaledContents), and QScrollArea's " "ability to automatically resize its contents " "(QScrollArea.widgetResizable), can be used to implement " "zooming and scaling features.</p>" "<p>In addition the example shows how to use QPainter to " "print an image.</p>") def createActions(self): self.openAct = QAction("&Open...", self, shortcut="Ctrl+O", triggered=self.open) self.printAct = QAction("&Print...", self, shortcut="Ctrl+P", enabled=False, triggered=self.print_) self.exitAct = QAction("E&xit", self, shortcut="Ctrl+Q", triggered=self.close) self.zoomInAct = QAction("Zoom &In (25%)", self, shortcut="Ctrl++", enabled=False, triggered=self.zoomIn) self.zoomOutAct = QAction("Zoom &Out (25%)", self, shortcut="Ctrl+-", enabled=False, triggered=self.zoomOut) self.normalSizeAct = QAction("&Normal Size", self, shortcut="Ctrl+S", enabled=False, triggered=self.normalSize) self.fitToWindowAct = QAction("&Fit to Window", self, enabled=False, checkable=True, shortcut="Ctrl+F", triggered=self.fitToWindow) self.aboutAct = QAction("&About", self, triggered=self.about) self.faceDetectAct = QAction("Face Detect",self,triggered=self.faceDetect,enabled=False) self.resizeAct = QAction("Resize",self,triggered=self.imgResize,enabled=False) self.rotateAct = QAction("Rotate", self,triggered=self.imgRotate, enabled=False) def createMenus(self): self.fileMenu = QMenu("&File", self) self.fileMenu.addAction(self.openAct) self.fileMenu.addAction(self.printAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.exitAct) self.viewMenu = QMenu("&View", self) self.viewMenu.addAction(self.zoomInAct) self.viewMenu.addAction(self.zoomOutAct) self.viewMenu.addAction(self.normalSizeAct) self.viewMenu.addSeparator() self.viewMenu.addAction(self.fitToWindowAct) self.optionsMenu = QMenu("&Options", self) self.optionsMenu.addAction(self.faceDetectAct) self.optionsMenu.addAction(self.resizeAct) self.optionsMenu.addAction(self.rotateAct) self.helpMenu = QMenu("&Help", self) self.helpMenu.addAction(self.aboutAct) self.menuBar().addMenu(self.fileMenu) self.menuBar().addMenu(self.viewMenu) self.menuBar().addMenu(self.optionsMenu) self.menuBar().addMenu(self.helpMenu) def updateActions(self): self.zoomInAct.setEnabled(not self.fitToWindowAct.isChecked()) self.zoomOutAct.setEnabled(not self.fitToWindowAct.isChecked()) self.normalSizeAct.setEnabled(not self.fitToWindowAct.isChecked()) self.resizeAct.setEnabled(not self.fitToWindowAct.isChecked()) self.faceDetectAct.setEnabled(not self.fitToWindowAct.isChecked()) self.rotateAct.setEnabled(not self.fitToWindowAct.isChecked()) def scaleImage(self, factor): self.scaleFactor *= factor self.imageLabel.resize(self.scaleFactor * self.imageLabel.pixmap().size()) self.adjustScrollBar(self.scrollArea.horizontalScrollBar(), factor) self.adjustScrollBar(self.scrollArea.verticalScrollBar(), factor) self.zoomInAct.setEnabled(self.scaleFactor < 3.0) self.zoomOutAct.setEnabled(self.scaleFactor > 0.333) def adjustScrollBar(self, scrollBar, factor): scrollBar.setValue(int(factor * scrollBar.value() + ((factor - 1) * scrollBar.pageStep()/2)))
class StateTooltip(QWidget): """ 进度提示框 """ def __init__(self, title="", content="", parent=None): """ Parameters ---------- title: str 状态气泡标题 content: str 状态气泡内容 parant: 父级窗口 """ super().__init__(parent) self.title = title self.content = content # 实例化小部件 self.titleLabel = QLabel(self.title, self) self.contentLabel = QLabel(self.content, self) self.rotateTimer = QTimer(self) self.closeTimer = QTimer(self) self.animation = QPropertyAnimation(self, b"windowOpacity") self.busyImage = QPixmap(":/images/state_tooltip/running.png") self.doneImage = QPixmap(":/images/state_tooltip/completed.png") self.closeButton = QToolButton(self) # 初始化参数 self.isDone = False self.rotateAngle = 0 self.deltaAngle = 20 # 初始化 self.__initWidget() def __initWidget(self): """ 初始化小部件 """ self.setAttribute(Qt.WA_StyledBackground) self.rotateTimer.setInterval(50) self.closeTimer.setInterval(1000) self.contentLabel.setMinimumWidth(200) # 将信号连接到槽函数 self.closeButton.clicked.connect(self.hide) # 点击关闭按钮只是隐藏了提示条 self.rotateTimer.timeout.connect(self.__rotateTimerFlowSlot) self.closeTimer.timeout.connect(self.__slowlyClose) self.__setQss() self.__initLayout() # 打开定时器 self.rotateTimer.start() def __initLayout(self): """ 初始化布局 """ self.titleLabel.adjustSize() self.contentLabel.adjustSize() self.setFixedSize(max(self.titleLabel.width(), self.contentLabel.width()) + 40, 64) self.titleLabel.move(40, 11) self.contentLabel.move(15, 34) self.closeButton.move(self.width() - 30, 23) def __setQss(self): """ 设置层叠样式 """ self.titleLabel.setObjectName("titleLabel") self.contentLabel.setObjectName("contentLabel") f = QFile(':/qss/state_tooltip.qss') f.open(QFile.ReadOnly) self.setStyleSheet(str(f.readAll(), encoding='utf-8')) f.close() def setTitle(self, title: str): """ 设置提示框的标题 """ self.title = title self.titleLabel.setText(title) self.titleLabel.adjustSize() def setContent(self, content: str): """ 设置提示框内容 """ self.content = content self.contentLabel.setText(content) self.contentLabel.adjustSize() def setState(self, isDone=False): """ 设置运行状态 """ self.isDone = isDone self.update() # 运行完成后主动关闭窗口 if self.isDone: self.closeTimer.start() def __slowlyClose(self): """ 缓慢关闭窗口 """ self.rotateTimer.stop() self.animation.setEasingCurve(QEasingCurve.Linear) self.animation.setDuration(500) self.animation.setStartValue(1) self.animation.setEndValue(0) self.animation.finished.connect(self.deleteLater) self.animation.start() def __rotateTimerFlowSlot(self): """ 定时器溢出时旋转箭头 """ self.rotateAngle = (self.rotateAngle + self.deltaAngle) % 360 self.update() def paintEvent(self, e): """ 绘制背景 """ super().paintEvent(e) painter = QPainter(self) painter.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform) painter.setPen(Qt.NoPen) if not self.isDone: painter.translate(24, 23) # 原点平移到旋转中心 painter.rotate(self.rotateAngle) # 坐标系旋转 painter.drawPixmap( -int(self.busyImage.width() / 2), -int(self.busyImage.height() / 2), self.busyImage, ) else: painter.drawPixmap(14, 13, self.doneImage.width(), self.doneImage.height(), self.doneImage)
class DynamicLabelBool(object): def __init__(self, window, settings): # Retrieve settings ### UI Related self._stylesheet = settings[ 'stylesheet'] if 'stylesheet' in settings and len( settings['stylesheet']) == 2 else ["", ""] geometry = settings['geometry'] if 'geometry' in settings else [ 0, 0, 7 ] pos = settings['pos'] if 'pos' in settings else [0, 0] alignment = settings['alignment'] if 'alignment' in settings else 7 self._evaluation = settings['evaluation'] if 'stylesheet' not in self._evaluation['true']: self._evaluation['true']['stylesheet'] = "" if 'stylesheet' not in self._evaluation['false']: self._evaluation['false']['stylesheet'] = "" if 'text' not in self._evaluation['true']: self._evaluation['true']['text'] = "" if 'text' not in self._evaluation['false']: self._evaluation['false']['text'] = "" ### Metric related self._metric = settings['metric'] self._is_true = False # Create components self._label = QLabel(window) self._label.setAttribute(Qt.WA_TranslucentBackground) # Get size of longest text self._label.setStyleSheet('QLabel{' + self._evaluation['true']['stylesheet'] + '}') self._label.setText(self._evaluation['true']['text']) self._label.adjustSize() size = [self._label.size().width(), self._label.fontMetrics().height()] self._label.setStyleSheet('QLabel{' + self._evaluation['false']['stylesheet'] + '}') self._label.setText(self._evaluation['false']['text']) self._label.adjustSize() size[0] = size[0] if self._label.size().width( ) < size[0] else self._label.size().width() # Process alignment if len(geometry) == 2: geometry.append(7) geometry.insert(2, size[0]) geometry.insert(3, size[1]) geometry, h_alignment = getPosFromGeometry(geometry) if h_alignment < 0: self._label.setAlignment(Qt.AlignLeft) elif h_alignment > 0: self._label.setAlignment(Qt.AlignRight) else: self._label.setAlignment(Qt.AlignHCenter) self._label.move(geometry[0], geometry[1]) self._label.show() def setParent(self, p): self._label.setParent(p) def deleteLater(self): self._label.deleteLater() def update(self, refresh=False): if refresh: if self._metric['name'][0][0] != "*": value = InternalMetrics().metrics # Navigate status json to desired metric for i in range(0, len(self._metric['name'])): if self._metric['name'][i] in value: value = value[self._metric['name'][i]] else: # Interrupt update if desired metric is not found return else: # Get computed metric value = InternalMetrics().metrics[self._metric['name'][0]] value = value[-1] is_true = (value == self._metric['target_value'] if self._metric['operator'] == '=' else (value > self._metric['target_value'] if self._metric['operator'] == '>' else (value < self._metric['target_value'] if self._metric['operator'] == '<' else False))) if is_true != self._is_true: if is_true: self._label.setText(self._evaluation['true']['text']) self._label.setStyleSheet( 'QLabel{' + self._evaluation['true']['stylesheet'] + '}') else: self._label.setText(self._evaluation['false']['text']) self._label.setStyleSheet( 'QLabel{' + self._evaluation['false']['stylesheet'] + '}') self._label.adjustSize() self._is_true = is_true
class NotificationItem(QWidget): closed = pyqtSignal(QListWidgetItem) def __init__(self, title, message, item, *args, ntype=0, callback=None, **kwargs): super(NotificationItem, self).__init__(*args, **kwargs) self.item = item self.callback = callback layout = QHBoxLayout(self, spacing=0) layout.setContentsMargins(0, 0, 0, 0) self.bgWidget = QWidget(self) # 背景控件, 用于支持动画效果 layout.addWidget(self.bgWidget) layout = QGridLayout(self.bgWidget) layout.setHorizontalSpacing(15) layout.setVerticalSpacing(10) # 标题左边图标 layout.addWidget( QLabel(self, pixmap=NotificationIcon.icon(ntype)), 0, 0) # 标题 self.labelTitle = QLabel(title, self) font = self.labelTitle.font() font.setBold(True) font.setPixelSize(22) self.labelTitle.setFont(font) # 关闭按钮 self.labelClose = QLabel( self, cursor=Qt.PointingHandCursor, pixmap=NotificationIcon.icon(NotificationIcon.Close)) # 消息内容 self.labelMessage = QLabel( message, self, cursor=Qt.PointingHandCursor, wordWrap=True, alignment=Qt.AlignLeft | Qt.AlignTop) font = self.labelMessage.font() font.setPixelSize(20) self.labelMessage.setFont(font) self.labelMessage.adjustSize() # 添加到布局 layout.addWidget(self.labelTitle, 0, 1) layout.addItem(QSpacerItem( 40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum), 0, 2) layout.addWidget(self.labelClose, 0, 3) layout.addWidget(self.labelMessage, 1, 1, 1, 2) # 边框阴影 effect = QGraphicsDropShadowEffect(self) effect.setBlurRadius(12) effect.setColor(QColor(0, 0, 0, 25)) effect.setOffset(0, 2) self.setGraphicsEffect(effect) self.adjustSize() # 5秒自动关闭 self._timer = QTimer(self, timeout=self.doClose) self._timer.setSingleShot(True) # 只触发一次 self._timer.start(5000) def doClose(self): try: # 可能由于手动点击导致item已经被删除了 self.closed.emit(self.item) except: pass def showAnimation(self, width): # 显示动画 pass def closeAnimation(self): # 关闭动画 pass def mousePressEvent(self, event): super(NotificationItem, self).mousePressEvent(event) w = self.childAt(event.pos()) if not w: return if w == self.labelClose: # 点击关闭图标 # 先尝试停止计时器 self._timer.stop() self.closed.emit(self.item) elif w == self.labelMessage and self.callback and callable(self.callback): # 点击消息内容 self._timer.stop() self.closed.emit(self.item) self.callback() # 回调 def paintEvent(self, event): # 圆角以及背景色 super(NotificationItem, self).paintEvent(event) painter = QPainter(self) path = QPainterPath() path.addRoundedRect(QRectF(self.rect()), 6, 6) painter.fillPath(path, Qt.white)
class Example(QMainWindow): # settings={} def __init__(self): super().__init__() self.movieObj = whole_movie() self.movieObj.signal.connect(self.update_status) self.movieObj.sig_tqdm.connect(self.update_tqdm) self.movieObj.sig_state.connect(self.update_state) self.initUI() def initUI(self): # self.initSettings() # self.settings = self.importSettings() self.statusBar() defaultFontSize = 10 # 左揃えのX座標 defaultLineLeft = 40 # メニューバーのアイコン設定 openFile = QAction('Open', self) # ショートカット設定 openFile.setShortcut('Ctrl+O') # ステータスバー設定 openFile.setStatusTip('Open new File') openFile.triggered.connect(self.showDialog) # メニューバー作成 menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(openFile) openFileButton = QPushButton("ファイルを開く", self) openFileButton.setFont(QFont('Arial', defaultFontSize)) openFileButton.move(defaultLineLeft, 48) openFileButton.clicked.connect(self.showDialog) self.openFileLabel = QLabel(self) self.openFileLabel.setFont(QFont('Arial', defaultFontSize)) self.openFileLabel.move(160, 53) self.openFileLabel.setText("ファイルが開かれていません") self.openFileLabel.adjustSize() self.writeWholeButton = QCheckBox('全試合を繋げた動画ファイル書き出す', self) self.writeWholeButton.toggle() self.writeWholeButton.move(defaultLineLeft, 200) self.writeWholeButton.adjustSize() self.forceExecButton = QCheckBox('前回のログを無視して再実行(非推奨)', self) self.forceExecButton.move(defaultLineLeft, 225) self.forceExecButton.adjustSize() executeButton = QPushButton("処理開始", self) executeButton.setFont(QFont('Arial', defaultFontSize)) executeButton.move(315, 98) # クリックされたらbuttonClickedの呼び出し executeButton.clicked.connect(self.requestButtonClicked) self.pbar = QProgressBar(self) # self.pbar.setTextVisible(False) self.pbar.setMinimumWidth(255) self.pbar.move(defaultLineLeft, 98) self.ETALabel = QLabel(self) self.ETALabel.move(defaultLineLeft + 120, 138) self.ETALabel.setMinimumWidth(120) self.ETALabel.setFont(QFont('Arial', defaultFontSize - 2)) self.stateLabel = QLabel(self) self.stateLabel.move(defaultLineLeft, 138) self.stateLabel.setMinimumWidth(120) self.stateLabel.setFont(QFont('Arial', defaultFontSize - 2)) self.setGeometry(300, 300, 450, 270) self.setWindowTitle('イカカット') self.show() def requestButtonClicked(self): # fname[0]は選択したファイルのパス(ファイル名を含む # self.exportSettings() self.exec_process() def showDialog(self): open_path = "c://" user_name = os.getlogin() # 第二引数はダイアログのタイトル、第三引数は表示するパス if os.path.exists("c://Users/" + user_name + "/Videos"): open_path = "c://Users/" + user_name + "/Videos" self.fname = QFileDialog.getOpenFileName( self, 'Open file', open_path, "Video files(*.mp4 *.mkv *.flv *.avi);;All files(*)") if self.fname[0]: self.openFileLabel.setText(self.fname[0]) self.openFileLabel.adjustSize() # def initSettings(self): # if not os.path.exists("settings.json"): # self.exportSettings() # def importSettings(self): # with open("settings.json") as sjson: # try: # sjson_load = json.load(sjson) # return sjson_load # except Exception as e: # return # def exportSettings(self): # self.settings={} # with open("settings.json","w") as sjson: # json.dump(self.settings,sjson) # def closeEvent(self, event): # self.exportSettings() @pyqtSlot(int) def update_status(self, progress): self.pbar.setValue(progress) # progressBarを進める @pyqtSlot(str) def update_tqdm(self, output): self.ETALabel.setText(output) @pyqtSlot(str) def update_state(self, output): self.stateLabel.setText(output) @pyqtSlot() def exec_process(self): if self.fname[0]: # ファイル読み込み self.movieObj.initialize(src_path=self.fname[0]) self.pbar.setValue(0) self.pbar.setMinimum(0) self.pbar.setMaximum(int(self.movieObj.num_of_frames)) self.movieObj.setOptions( force_exec=self.forceExecButton.checkState(), write_clips=1, write_whole=self.writeWholeButton.checkState()) self.movieObj.start()
class Dialog(QDialog): def __init__(self): super().__init__() self.initdiagUI() def initdiagUI(self): exitShortcut = QShortcut(QKeySequence('Ctrl+W'), self, qApp.quit) #=====# #=====# #=====# #=====# #=====# #=====# # Create local seperate connection to databse #=====# #=====# #=====# #=====# #=====# #=====# self.db = QSqlDatabase.database("dialog") #=====# #=====# #=====# #=====# #=====# #=====# # Create SqlRecord template with predefined fields #=====# #=====# #=====# #=====# #=====# #=====# self.record_template = QSqlRecord() self.record_template.insert(0, QSqlField('model')) self.record_template.insert(1, QSqlField('order_quantity')) self.record_template.insert(2, QSqlField('order_time')) self.record_template.insert(3, QSqlField('expected_production')) #=====# #=====# #=====# #=====# #=====# #=====# # Main widgets #=====# #=====# #=====# #=====# #=====# #=====# label_model = QLabel('Model', self) label_model.move(40, 50) self.combo = QComboBox(self) self.fillcombo() self.combo.move(180, 50) label_orderquantity = QLabel('Order Quantity', self) label_orderquantity.move(40, 100) self.oq_input = QLineEdit('', self) self.oq_input.move(180, 100) self.error_message = QLabel('', self) self.error_message.move(180, 130) btn_submit = QPushButton('Submit Order', self) btn_submit.move(180, 150) btn_submit.clicked.connect(self.submittodb) self.setFixedSize(350, 200) self.setWindowTitle('Input Dialog') self.show() self.new_record = -1 #=====# #=====# #=====# #=====# #=====# #=====# #=====# #=====# #=====# #=====# #=====# #=====# # METHODS # #=====# #=====# #=====# #=====# #=====# #=====# #=====# #=====# #=====# #=====# #=====# #=====# #=====# #=====# #=====# #=====# #=====# #=====# #Populate combo box with model names using QSqlQuery and QSqlRecord objects #=====# #=====# #=====# #=====# #=====# #=====# def fillcombo(self): q = QSqlQuery("select name from models", self.db) self.rec = q.record() nameCol = self.rec.indexOf("name") print(nameCol) while q.next(): self.combo.addItem(q.value(nameCol)) #=====# #=====# #=====# #=====# #=====# #=====# #Submit input data to the model in database #=====# #=====# #=====# #=====# #=====# #=====# def submittodb(self): #print ('Inside label: ', self.oq_input.text()) if self.oq_input.text().isdigit(): self.new_record = QSqlRecord(self.record_template) self.new_record.setValue(0, self.combo.currentText()) self.new_record.setValue(1, self.oq_input.text()) self.new_record.setValue(2, str(datetime.datetime.now())) self.close() else: self.error_message.setText('Please enter an integer only') self.error_message.adjustSize() self.error_message.setStyleSheet("color:red")
class PixmapDiagram(E5MainWindow): """ Class implementing a dialog showing a pixmap. """ ZoomLevels = [ 1, 3, 5, 7, 9, 10, 20, 30, 50, 67, 80, 90, 100, 110, 120, 133, 150, 170, 200, 240, 300, 400, 500, 600, 700, 800, 900, 1000, ] ZoomLevelDefault = 100 def __init__(self, pixmap, parent=None, name=None): """ Constructor @param pixmap filename of a graphics file to show (string) @param parent parent widget of the view (QWidget) @param name name of the view widget (string) """ super(PixmapDiagram, self).__init__(parent) if name: self.setObjectName(name) else: self.setObjectName("PixmapDiagram") self.setWindowTitle(self.tr("Pixmap-Viewer")) self.pixmapLabel = QLabel() self.pixmapLabel.setObjectName("pixmapLabel") self.pixmapLabel.setBackgroundRole(QPalette.Base) self.pixmapLabel.setSizePolicy( QSizePolicy.Ignored, QSizePolicy.Ignored) self.pixmapLabel.setScaledContents(True) self.pixmapView = QScrollArea() self.pixmapView.setObjectName("pixmapView") self.pixmapView.setBackgroundRole(QPalette.Dark) self.pixmapView.setWidget(self.pixmapLabel) self.setCentralWidget(self.pixmapView) self.__zoomWidget = E5ZoomWidget( UI.PixmapCache.getPixmap("zoomOut.png"), UI.PixmapCache.getPixmap("zoomIn.png"), UI.PixmapCache.getPixmap("zoomReset.png"), self) self.statusBar().addPermanentWidget(self.__zoomWidget) self.__zoomWidget.setMapping( PixmapDiagram.ZoomLevels, PixmapDiagram.ZoomLevelDefault) self.__zoomWidget.valueChanged.connect(self.__doZoom) # polish up the dialog self.resize(QSize(800, 600).expandedTo(self.minimumSizeHint())) self.pixmapfile = pixmap self.status = self.__showPixmap(self.pixmapfile) self.__initActions() self.__initContextMenu() self.__initToolBars() self.grabGesture(Qt.PinchGesture) def __initActions(self): """ Private method to initialize the view actions. """ self.closeAct = \ QAction(UI.PixmapCache.getIcon("close.png"), self.tr("Close"), self) self.closeAct.triggered.connect(self.close) self.printAct = \ QAction(UI.PixmapCache.getIcon("print.png"), self.tr("Print"), self) self.printAct.triggered.connect(self.__printDiagram) self.printPreviewAct = \ QAction(UI.PixmapCache.getIcon("printPreview.png"), self.tr("Print Preview"), self) self.printPreviewAct.triggered.connect(self.__printPreviewDiagram) def __initContextMenu(self): """ Private method to initialize the context menu. """ self.__menu = QMenu(self) self.__menu.addAction(self.closeAct) self.__menu.addSeparator() self.__menu.addAction(self.printPreviewAct) self.__menu.addAction(self.printAct) self.setContextMenuPolicy(Qt.CustomContextMenu) self.customContextMenuRequested.connect(self.__showContextMenu) def __showContextMenu(self, coord): """ Private slot to show the context menu of the listview. @param coord the position of the mouse pointer (QPoint) """ self.__menu.popup(self.mapToGlobal(coord)) def __initToolBars(self): """ Private method to populate the toolbars with our actions. """ self.windowToolBar = QToolBar(self.tr("Window"), self) self.windowToolBar.setIconSize(UI.Config.ToolBarIconSize) self.windowToolBar.addAction(self.closeAct) self.graphicsToolBar = QToolBar(self.tr("Graphics"), self) self.graphicsToolBar.setIconSize(UI.Config.ToolBarIconSize) self.graphicsToolBar.addAction(self.printPreviewAct) self.graphicsToolBar.addAction(self.printAct) self.addToolBar(Qt.TopToolBarArea, self.windowToolBar) self.addToolBar(Qt.TopToolBarArea, self.graphicsToolBar) def __showPixmap(self, filename): """ Private method to show a file. @param filename name of the file to be shown (string) @return flag indicating success (boolean) """ image = QImage(filename) if image.isNull(): E5MessageBox.warning( self, self.tr("Pixmap-Viewer"), self.tr( """<p>The file <b>{0}</b> cannot be displayed.""" """ The format is not supported.</p>""").format(filename)) return False self.pixmapLabel.setPixmap(QPixmap.fromImage(image)) self.pixmapLabel.adjustSize() return True def getDiagramName(self): """ Public method to retrieve a name for the diagram. @return name for the diagram """ return self.pixmapfile def getStatus(self): """ Public method to retrieve the status of the canvas. @return flag indicating a successful pixmap loading (boolean) """ return self.status def wheelEvent(self, evt): """ Protected method to handle wheel events. @param evt reference to the wheel event (QWheelEvent) """ if evt.modifiers() & Qt.ControlModifier: if qVersion() >= "5.0.0": delta = evt.angleDelta().y() else: delta = evt.delta() if delta < 0: self.__zoomOut() else: self.__zoomIn() evt.accept() return super(PixmapDiagram, self).wheelEvent(evt) def event(self, evt): """ Public method handling events. @param evt reference to the event (QEvent) @return flag indicating, if the event was handled (boolean) """ if evt.type() == QEvent.Gesture: self.gestureEvent(evt) return True return super(PixmapDiagram, self).event(evt) def gestureEvent(self, evt): """ Protected method handling gesture events. @param evt reference to the gesture event (QGestureEvent """ pinch = evt.gesture(Qt.PinchGesture) if pinch: if pinch.state() == Qt.GestureStarted: pinch.setScaleFactor(self.__zoom() / 100) else: self.__doZoom(int(pinch.scaleFactor() * 100)) evt.accept() ########################################################################### ## Private menu handling methods below. ########################################################################### def __adjustScrollBar(self, scrollBar, factor): """ Private method to adjust a scrollbar by a certain factor. @param scrollBar reference to the scrollbar object (QScrollBar) @param factor factor to adjust by (float) """ scrollBar.setValue(int(factor * scrollBar.value() + ((factor - 1) * scrollBar.pageStep() / 2))) def __levelForZoom(self, zoom): """ Private method determining the zoom level index given a zoom factor. @param zoom zoom factor (integer) @return index of zoom factor (integer) """ try: index = PixmapDiagram.ZoomLevels.index(zoom) except ValueError: for index in range(len(PixmapDiagram.ZoomLevels)): if zoom <= PixmapDiagram.ZoomLevels[index]: break return index def __doZoom(self, value): """ Private method to set the zoom value in percent. @param value zoom value in percent (integer) """ oldValue = self.__zoom() if value != oldValue: self.pixmapLabel.resize( value / 100 * self.pixmapLabel.pixmap().size()) factor = value / oldValue self.__adjustScrollBar( self.pixmapView.horizontalScrollBar(), factor) self.__adjustScrollBar( self.pixmapView.verticalScrollBar(), factor) self.__zoomWidget.setValue(value) def __zoomIn(self): """ Private method to zoom into the pixmap. """ index = self.__levelForZoom(self.__zoom()) if index < len(PixmapDiagram.ZoomLevels) - 1: self.__doZoom(PixmapDiagram.ZoomLevels[index + 1]) def __zoomOut(self): """ Private method to zoom out of the pixmap. """ index = self.__levelForZoom(self.__zoom()) if index > 0: self.__doZoom(PixmapDiagram.ZoomLevels[index - 1]) def __zoomReset(self): """ Private method to reset the zoom value. """ self.__doZoom(PixmapDiagram.ZoomLevels[PixmapDiagram.ZoomLevelDefault]) def __zoom(self): """ Private method to get the current zoom factor in percent. @return current zoom factor in percent (integer) """ return int(self.pixmapLabel.width() / self.pixmapLabel.pixmap().width() * 100.0) def __printDiagram(self): """ Private slot called to print the diagram. """ printer = QPrinter(mode=QPrinter.ScreenResolution) printer.setFullPage(True) if Preferences.getPrinter("ColorMode"): printer.setColorMode(QPrinter.Color) else: printer.setColorMode(QPrinter.GrayScale) if Preferences.getPrinter("FirstPageFirst"): printer.setPageOrder(QPrinter.FirstPageFirst) else: printer.setPageOrder(QPrinter.LastPageFirst) printer.setPrinterName(Preferences.getPrinter("PrinterName")) printDialog = QPrintDialog(printer, self) if printDialog.exec_(): self.__print(printer) def __printPreviewDiagram(self): """ Private slot called to show a print preview of the diagram. """ from PyQt5.QtPrintSupport import QPrintPreviewDialog printer = QPrinter(mode=QPrinter.ScreenResolution) printer.setFullPage(True) if Preferences.getPrinter("ColorMode"): printer.setColorMode(QPrinter.Color) else: printer.setColorMode(QPrinter.GrayScale) if Preferences.getPrinter("FirstPageFirst"): printer.setPageOrder(QPrinter.FirstPageFirst) else: printer.setPageOrder(QPrinter.LastPageFirst) printer.setPageMargins( Preferences.getPrinter("LeftMargin") * 10, Preferences.getPrinter("TopMargin") * 10, Preferences.getPrinter("RightMargin") * 10, Preferences.getPrinter("BottomMargin") * 10, QPrinter.Millimeter ) printer.setPrinterName(Preferences.getPrinter("PrinterName")) preview = QPrintPreviewDialog(printer, self) preview.paintRequested[QPrinter].connect(self.__print) preview.exec_() def __print(self, printer): """ Private slot to the actual printing. @param printer reference to the printer object (QPrinter) """ painter = QPainter() painter.begin(printer) # calculate margin and width of printout font = QFont("times", 10) painter.setFont(font) fm = painter.fontMetrics() fontHeight = fm.lineSpacing() marginX = printer.pageRect().x() - printer.paperRect().x() marginX = Preferences.getPrinter("LeftMargin") * \ int(printer.resolution() / 2.54) - marginX marginY = printer.pageRect().y() - printer.paperRect().y() marginY = Preferences.getPrinter("TopMargin") * \ int(printer.resolution() / 2.54) - marginY width = printer.width() - marginX - \ Preferences.getPrinter("RightMargin") * \ int(printer.resolution() / 2.54) height = printer.height() - fontHeight - 4 - marginY - \ Preferences.getPrinter("BottomMargin") * \ int(printer.resolution() / 2.54) # write a foot note s = self.tr("Diagram: {0}").format(self.getDiagramName()) tc = QColor(50, 50, 50) painter.setPen(tc) painter.drawRect(marginX, marginY, width, height) painter.drawLine(marginX, marginY + height + 2, marginX + width, marginY + height + 2) painter.setFont(font) painter.drawText(marginX, marginY + height + 4, width, fontHeight, Qt.AlignRight, s) # render the diagram size = self.pixmapLabel.pixmap().size() size.scale(QSize(width - 10, height - 10), # 5 px inner margin Qt.KeepAspectRatio) painter.setViewport(marginX + 5, marginY + 5, size.width(), size.height()) painter.setWindow(self.pixmapLabel.pixmap().rect()) painter.drawPixmap(0, 0, self.pixmapLabel.pixmap()) painter.end()
class Example(QWidget): trigger = QtCore.pyqtSignal() def __init__(self, parent=None): super().__init__(parent, QtCore.Qt.Window) self.top_warehouse = QFrame(self) self.top_warehouse.setFrameShape(QFrame.StyledPanel) self.top_warehouse.resize(584, 75) self.top_warehouse.move(8, 10) self.top_route = QFrame(self) self.top_route.setFrameShape(QFrame.StyledPanel) self.top_route.resize(584, 170) self.top_route.move(8, 88) self.top_supply = QFrame(self) self.top_supply.setFrameShape(QFrame.StyledPanel) self.top_supply.resize(285, 110) self.top_supply.move(10, 92) self.top_consumption = QFrame(self) self.top_consumption.setFrameShape(QFrame.StyledPanel) self.top_consumption.resize(286, 110) self.top_consumption.move(304, 92) self.combo_route = QComboBox(self) self.combo_route.addItems(['1', '2', '3']) self.combo_route.move(150, 220) self.combo_route.resize(self.combo_route.sizeHint()) """ Data entry for supply """ pars = parsing_tuple() self.combo_supply = QComboBox(self) self.combo_supply.addItems(pars) self.combo_weight_party = QComboBox(self) self.combo_weight_party.addItems(['20', '30', '40']) self.date_supply = QDateTimeEdit() vbox = QVBoxLayout() layout = QHBoxLayout(self) layout.addLayout(vbox) layout.addWidget(self.combo_supply) layout.addWidget(self.combo_weight_party) layout.addWidget(self.date_supply) layout.addStretch(1) """ Data entry for warehouse """ self.combo_warehouse = QComboBox(self) self.combo_warehouse.addItems(pars) self.combo_warehouse.move(150, 30) self.combo_warehouse.resize(self.combo_warehouse.sizeHint()) self.lbl_warehouse = QLabel("Склады", self) self.lbl_warehouse.move(300, 30) """ Data entry for consumption """ self.combo_consumption = QComboBox(self) self.combo_consumption.addItems(pars) self.date_consumption = QDateTimeEdit() layout.addWidget(self.combo_consumption) layout.addWidget(self.date_consumption) self.check_route() self.check_warehouse() self.initUI() def initUI(self): btn_input = QPushButton('Ввести значения', self) btn_input.resize(btn_input.sizeHint()) btn_input.move(420, 220) btn_input.clicked.connect(self.get_supply_consumption) btn_delete_route = QPushButton('Удалить маршруты', self) btn_delete_route.resize(btn_delete_route.sizeHint()) btn_delete_route.move(310, 220) btn_delete_route.clicked.connect(self.delete_route) btn_delete_warehouse = QPushButton('Удалить склады', self) btn_delete_warehouse.resize(btn_delete_warehouse.sizeHint()) btn_delete_warehouse.move(490, 55) btn_delete_warehouse.clicked.connect(self.delete_warehouse) btn_add_warehouse = QPushButton('Добавить склад', self) btn_add_warehouse.resize(btn_delete_route.sizeHint()) btn_add_warehouse.move(40, 30) btn_add_warehouse.clicked.connect(self.update_warehouse) lbl_route = QLabel("Маршрут:", self) lbl_route.resize(lbl_route.sizeHint()) lbl_route.move(100, 220) lbl_supply = QLabel("Точка поставки", self) lbl_supply.resize((lbl_supply.sizeHint())) lbl_supply.move(90, 93) lbl_consupmtion = QLabel("Точка потребления", self) lbl_consupmtion.resize(lbl_consupmtion.sizeHint()) lbl_consupmtion.move(450, 93) lbl_supply_point = QLabel("Пункт", self) lbl_supply_point.resize(lbl_supply_point.sizeHint()) lbl_supply_point.move(25, 115) lbl_weight_party = QLabel("Вес партии", self) lbl_weight_party.resize(lbl_weight_party.sizeHint()) lbl_weight_party.move(70, 115) lbl_date_departure = QLabel("Дата отправления", self) lbl_date_departure.resize(lbl_date_departure.sizeHint()) lbl_date_departure.move(145, 115) lbl_consumption_point = QLabel("Пункт", self) lbl_consumption_point.resize(lbl_consumption_point.sizeHint()) lbl_consumption_point.move(420, 115) lbl_date_arrival = QLabel("Дата прибытия", self) lbl_date_arrival.resize(lbl_date_arrival.sizeHint()) lbl_date_arrival.move(490, 115) self.setGeometry(300, 300, 600, 300) self.setWindowTitle('Выбрать параметры поставки груза') def check_route(self): routs, session = session_getting_route() before_route = 0 for route in routs: if before_route != route.num_route: self.combo_route.removeItem(route.num_route - 1) before_route = route.num_route session.close() def delete_warehouse(self): session_delete_warehouse() self.check_warehouse() pars = parsing_tuple() self.combo_warehouse.clear() self.combo_supply.clear() self.combo_consumption.clear() self.combo_warehouse.addItems(pars) self.combo_supply.addItems(pars) self.combo_consumption.addItems(pars) def delete_route(self): """ delete data before use program :return: nothing """ session_clear_field() self.trigger.emit() pars = parsing_tuple() self.combo_warehouse.clear() self.combo_supply.clear() self.combo_consumption.clear() self.combo_route.clear() self.combo_warehouse.addItems(pars) self.combo_supply.addItems(pars) self.combo_consumption.addItems(pars) main() self.combo_route.addItems(['1', '2', '3']) def check_warehouse(self): str_warehouse = 'Склады:' name_warehouse = session_get_warehouse() for warehouse in name_warehouse: str_warehouse = str_warehouse + warehouse.name_point + ',' self.lbl_warehouse.setText(str_warehouse) self.lbl_warehouse.adjustSize() def update_warehouse(self): warehouse = self.combo_warehouse.currentText() session_add_warehouse(warehouse) self.check_warehouse() pars = parsing_tuple() self.combo_warehouse.clear() self.combo_supply.clear() self.combo_consumption.clear() self.combo_warehouse.addItems(pars) self.combo_supply.addItems(pars) self.combo_consumption.addItems(pars) def get_supply_consumption(self): """ Data collection from forms :return: nothing """ supply = self.combo_supply.currentText() consumption = self.combo_consumption.currentText() route = self.combo_route.currentText() date_arrival = datetime.datetime( int(self.date_consumption.dateTime().toString("yyyy")), int(self.date_consumption.dateTime().toString("MM")), int(self.date_consumption.dateTime().toString("dd")), int(self.date_consumption.dateTime().toString("hh"))) date_departure = datetime.datetime( int(self.date_supply.dateTime().toString("yyyy")), int(self.date_supply.dateTime().toString("MM")), int(self.date_supply.dateTime().toString("dd")), int(self.date_supply.dateTime().toString("hh"))) weight = int(self.combo_weight_party.currentText()) loading = loading_party(weight) id_supply, num_party, empty_truck = session_create2( weight=weight, supply=supply, date=date_departure, loading=loading) unloading = unloading_party(weight) travel_time = date_arrival - date_departure id_consumption = session_add_consumption(consumption=consumption, date=date_arrival, unloading=unloading, party=num_party, travel_time=travel_time.days, weight=weight) agent = session_get_next_point() parsing(agent) if travel_time.days > 1: optimal_route, warehouse_point = search_route_warehouse( id_supply, id_consumption) session_add_warehouse_party(optimal_route, warehouse_point, num_party, loading, unloading) else: optimal_route = dijkstra(id_supply, id_consumption) lst_pars = lst_optimal(optimal_route) session_add_route(lst_pars, route, id_supply, empty_truck) update_graphic() self.trigger.emit() self.check_route()
class Example(QMainWindow): def crop(self, x,y,width,height): x = round(x * 1/self.ratio) y = round(y * 1/self.ratio) width = round(width * 1/self.ratio) height = round(height * 1/self.ratio) from PIL import Image img = Image.open(self.imagepath) img2 = img.crop((x, y, x+width, y+height)) basepath = os.path.dirname(self.imagepath) if basepath == "": basepath = "." img2.save(basepath + "/cropped" + os.path.basename(self.imagepath)) self.close() def __init__(self, imagepath, binpath): super().__init__() QToolTip.setFont(QFont('SansSerif', 10)) self.setToolTip('This is a <b>QWidget</b> widget') self.imageLabel = QLabel(self) self.imageLabel.setBackgroundRole(QPalette.Base) self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.imageLabel.setScaledContents(True) self.overlay = Overlay(self.imageLabel, binpath) self.setCentralWidget(self.overlay) self.overlay.c.cropImage.connect(self.crop) #self.overlay.setSizePolicy(QSizePolicy.Maximum,QSizePolicy.Maximum) self.imagepath = imagepath image = QPixmap(imagepath) w = image.width() h = image.height() rec = QApplication.desktop().screenGeometry(); dsk_h = rec.height(); dsk_w = rec.width(); wdw_w = min(0.7 * dsk_w, w) # Window's width 85% of screen's size self.ratio = wdw_w / w # Storing the ratio for later use wdw_h = h * self.ratio # A simple proportion to get the height, because we want to mantain the aspect ratio image = image.scaled(wdw_w, wdw_h, transformMode=QtCore.Qt.SmoothTransformation) self.imageLabel.setPixmap(image) self.imageLabel.adjustSize() self.setGeometry(dsk_w/2 - wdw_w/2, dsk_h/2 - wdw_h/2, wdw_w, wdw_h) self.setWindowTitle('Tooltips') self.show()