class MainWindow_EXEC(): def __init__(self): app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(MainWindow) self.update_calendar() self.update_progressbar() MainWindow.show() sys.exit(app.exec_()) def update_calendar(self): self.ui.calendarWidget.selectionChanged.connect(self.update_date) def update_date(self): self.ui.dateEdit.setDate(self.ui.calendarWidget.selectedDate()) def update_progressbar(self): radio3 = self.ui.Select.text() self.ui.Select.setText('Set Progressbar') radio3_upd = self.ui.Select.text() print(radio3, radio3_upd) self.ui.Select.clicked.connect(self.set_progressbar) def set_progressbar(self): progress_value = self.ui.progressBar.value() print('progressBar: ', progress_value) new_value = self.ui.lcdNumber.value() self.ui.progressBar.setValue(new_value) print('progressBar: ', self.ui.progressBar.value())
class MyApp(QtWidgets.QMainWindow): def __init__(self): super(MyApp, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.btnAdd.clicked.connect(self.Result) self.ui.BtnSubstract .clicked.connect(self.Result) self.ui.BtnDivide.clicked.connect(self.Result) self.ui.btnMultiply.clicked.connect(self.Result) def Result(self): sender = self.sender() result = 00 if sender.text() == "+": result = int(self.ui.txt1.text()) + int(self.ui.txt2.text()) elif sender.text() == "-": result = int(self.ui.txt1.text()) - int(self.ui.txt2.text()) elif sender.text() == "*": result = int(self.ui.txt1.text()) / int(self.ui.txt2.text()) elif sender.text() == "/": result = int(self.ui.txt1.text()) * int(self.ui.txt2.text()) self.ui.lblResult.setText("Result: "+ str(result))
class HesapMakinesi(QtWidgets.QMainWindow): def __init__(self): super(HesapMakinesi, self).__init__() #Buton tıklama işlemleri yapılacak olan kodlar ve arayüz. self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.btn_topla.clicked.connect(self.toplama) self.ui.btn_cikarma.clicked.connect(self.cikarma) self.ui.btn_carpma.clicked.connect(self.carpma) self.ui.btn_bolme.clicked.connect(self.bolme) def toplama(self): result = int(self.ui.txt_sayi1.text()) + int( self.ui.txt_sayi2.text()) # toplama işlmeminin yapıldığı dizin self.ui.lbl_sonuc.setText('sonuç: ' + str(result)) def cikarma(self): result = int(self.ui.txt_sayi1.text()) - int( self.ui.txt_sayi2.text()) # çıkarma işlemini yaptığım dizin self.ui.lbl_sonuc.setText('sonuç :' + str(result)) def bolme(self): result = int(self.ui.txt_sayi1.text()) / int( self.ui.txt_sayi2.text()) # bölme işlemi lokasyonu self.ui.lbl_sonuc.setText('sonuç : ' + str(result)) def carpma(self): result = int(self.ui.txt_sayi1.text()) * int( self.ui.txt_sayi2.text()) # çarpma işlemi yapılan dizin self.ui.lbl_sonuc.setText('sonuç : ' + str(result))
class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.window = Ui_MainWindow() self.window.setupUi(self) self.show() #################################### self.Tracker_Window = TrackerWindow() #################################### self.window.AccesButton.clicked.connect(self.show_tracker_window) self.window.helpButton.installEventFilter(self) def show_tracker_window(self): if len(self.window.emailText.text()) == 0: QMessageBox.about(self, "eMag Price Tracker", "Please enter a valid email address!") else: self.hide() self.Tracker_Window.email = self.window.emailText.text() self.Tracker_Window.show() def eventFilter(self, object, event): if object == self.window.helpButton and event.type( ) == QtCore.QEvent.HoverEnter: QMessageBox.about( self, "eMag Price Tracker", "Enter your valid email and start tracking. Add links for your products, create a preset, load it, and start tracking!" ) return False
class MyApp(QtWidgets.QMainWindow): def __init__(self): super(MyApp,self).__init__() # herhangi bir text label butona ulaşmak istediğimizde artık self.ui ile ulaşacağız (self.ui.txt_sayi2) gibi self.ui=Ui_MainWindow() self.ui.setupUi(self) # app projemize designerdaki elemanlar aktarılsın # click atamalarını burada yapıyoruz self.ui.btn_topla.clicked.connect(self.hesapla) self.ui.btn_cikarma.clicked.connect(self.hesapla) self.ui.btn_bolme.clicked.connect(self.hesapla) self.ui.btn_carpma.clicked.connect(self.hesapla) def hesapla(self): sender=self.sender().text() print(sender) result=0 if sender=="Toplam": result=int(self.ui.txt_sayi1.text()) + int(self.ui.txt_sayi2.text()) elif sender=='Çıkarma': result=int(self.ui.txt_sayi1.text()) - int(self.ui.txt_sayi2.text()) elif sender=="Çarpma": result=int(self.ui.txt_sayi1.text()) * int(self.ui.txt_sayi2.text()) elif sender=="Bölme": result=int(self.ui.txt_sayi1.text()) / int(self.ui.txt_sayi2.text()) self.ui.lbl_sonuc.setText("Sonuc: "+str(result))
class App(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.connect_button.clicked.connect(self.start) self.ui.send_button.clicked.connect(self.send_msg) self.client = None def start(self): server = self.ui.server_text.text() username = self.ui.user_text.text() self.client = Client(username, server) self.client.new_message.connect(self.print_msg) self.ui.chat_text.setEnabled(True) self.ui.message_text.setEnabled(True) self.ui.send_button.setEnabled(True) def send_msg(self): message = self.ui.message_text.text() self.ui.message_text.clear() self.client.send(message) def print_msg(self, message): self.ui.chat_text.append(message)
class MyMainW(QtGui.QMainWindow): DB = None def __init__(self, db,parent=None): MyMainW.DB=db QtGui.QMainWindow.__init__(self,parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.lineEdit.setText(time.strftime('%Y-%m-%d ',time.localtime(time.time()))) str="Welcome! Happy Every Day!" self.ui.textEdit.setText(str) QtCore.QObject.connect(self.ui.action_2,QtCore.SIGNAL("triggered()"),self.openBookInfo) QtCore.QObject.connect(self.ui.action_3,QtCore.SIGNAL("triggered()"),self.openSupplierInfo) QtCore.QObject.connect(self.ui.action_4,QtCore.SIGNAL("triggered()"),self.openCusInfo) QtCore.QObject.connect(self.ui.action_5,QtCore.SIGNAL("triggered()"),self.openAddBookInfo) QtCore.QObject.connect(self.ui.action_6,QtCore.SIGNAL("triggered()"),self.openStockInfo) QtCore.QObject.connect(self.ui.action_7,QtCore.SIGNAL("triggered()"),self.openAboutInfo) def openAboutInfo(self): message = QtGui.QMessageBox(self) message.setText("version:2.0\nCopyright (c) 2012 Lv Kaiyang") message.exec_() def openStockInfo(self): MyStockInfo(MyMainW.DB,self).show() def openAddBookInfo(self): row=[] MyAABook(MyMainW.DB,self,row).show() def openBookInfo(self): MyBookInfo(MyMainW.DB,self).show() def openSupplierInfo(self): MySupplierInfo(MyMainW.DB,self).show() def openCusInfo(self): MyCusInfo(MyMainW.DB,self).show()
class MyWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # Меняет размер всех колонок. self.ui.tableWidget.horizontalHeader().setSectionResizeMode(3) # self.ui.tableWidget.horizontalHeader().setMinimumSectionSize(1) self.machines = [] row = 0 for i in self.machines: a = QtWidgets.QTableWidgetItem() a.setData(Qt.DisplayRole, i) self.ui.tableWidget.setItem(row, 0, a) a = QtWidgets.QTableWidgetItem() a.setData(10, 2) self.ui.tableWidget.setItem(row, 1, a) a = QtWidgets.QTableWidgetItem() a.setData(Qt.DisplayRole, 'free') self.ui.tableWidget.setItem(row, 2, a) row += 1 def main_logic(self): client = Client() self.machines = client.machine_list client.set_up('localhost', 5001) client.start()
class notifyerForm(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self,parent) self.ui = Ui_MainWindow() self.ui.setupUi(self connect(self.ui.pushButtonStart, QtCore.SIGNAL("clicked()"), self.startuj) def startuj(self): pageAddress = self.ui.lineEditAddressil.text destinEmail = self.ui.lineEditDestinationEmail.text passwordEmail = self.ui.lineEditPassword.text loginEmail = self.lineEditPassword.text message = pageAddress+" zmienila sie tresc! Pzdr" watcher(pageAddress, destinEmail, message, loginEmail, passwordEmail ) sys.exit() if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = notifyerForm() myapp.show() sys.exit(app.exec())
def setupUi(self, MainWindow, pat): Ui_MainWindow.setupUi(self, MainWindow) #print(Mediator.showRecord(op_no)) self.mainwindow = MainWindow self.patient = pat (op_no, name, weight, height, pulse, bp, occu, ph_no, sex, age, place, hos) = self.patient.show() self.op_no.setReadOnly(True) self.op_no.setText(op_no) self.name.setReadOnly(True) self.name.setText(name) self.age.setReadOnly(True) self.age.setText(age) self.sex.setReadOnly(True) self.sex.setText(sex) self.place.setReadOnly(True) self.place.setText(place) self.ph_no.setReadOnly(True) self.ph_no.setText(ph_no) self.weight.setReadOnly(True) self.weight.setText(weight) self.pulse.setReadOnly(True) self.pulse.setText(pulse) self.bp.setReadOnly(True) self.bp.setText(bp) self.height.setReadOnly(True) self.height.setText(height) self.occu.setReadOnly(True) self.occu.setText(occu) self.hos.setReadOnly(True) self.hos.setText(hos) self.nextButton.clicked.connect(self.nextWindow)
class MyApp(QtWidgets.QMainWindow): def __init__(self): super(MyApp, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.btn_toplama.clicked.connect(self.hesapla) self.ui.btn_cikarma.clicked.connect(self.hesapla) self.ui.btn_carmpa.clicked.connect(self.hesapla) self.ui.btn_bolma.clicked.connect(self.hesapla) def hesapla(self): sender = self.sender().text() result = 0 if sender == "Toplama": result = int(self.ui.txt_sayi1.text()) + int( self.ui.txt_sayi2.text()) elif sender == "Çıkarma": result = int(self.ui.txt_sayi1.text()) - int( self.ui.txt_sayi2.text()) elif sender == "Çarpma": result = int(self.ui.txt_sayi1.text()) * int( self.ui.txt_sayi2.text()) elif sender == "Bölme": result = int(self.ui.txt_sayi1.text()) / int( self.ui.txt_sayi2.text()) self.ui.lbl_sonuc.setText("Sonuç: " + str(result))
class CalcApp(QtWidgets.QMainWindow): def __init__(self): super(CalcApp, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.btn_equal.clicked.connect(self.showCountResult) self.ui.btn_ce.clicked.connect(self.clear) self.ui.text_line.textChanged.connect(self.textChanged) self.showClickResult() def showClickResult(self): regExp = QtCore.QRegExp("btn_([0-9])|(add)|(sub)|(mul)|(div)") buttons = self.ui.centralwidget.findChildren(QtWidgets.QPushButton, regExp) for i in buttons: i.clicked.connect(self.btnInput) def showCountResult(self): self.ui.text_line.setText(countMethods.count(self.ui.text_line.text())) def clear(self): self.ui.text_line.clear() self.ui.text_line.setFocus() def btnInput(self): text = self.ui.text_line.text() + self.sender().text() self.ui.text_line.setText(text) def keyPressEvent(self, event): if event.key() in [QtCore.Qt.Key_Equal, QtCore.Qt.Key_Enter]: self.showCountResult() def textChanged(self): self.ui.text_line.setText(methods.verifyText(self.ui.text_line.text()))
class myApp(QtWidgets.QMainWindow): def __init__(self): super(myApp, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.btn_topla.clicked.connect(self.hesapla) self.ui.btn_cikarma.clicked.connect(self.hesapla) self.ui.btn_carpma.clicked.connect(self.hesapla) self.ui.btn_bolme.clicked.connect(self.hesapla) def hesapla(self): sender = self.sender().text() result = 0 if sender == 'Toplam': result = int(self.ui.txt_sayi1.text()) + int(self.ui.txt_sayi2.text()) elif sender == 'Cikarma': result = int(self.ui.txt_sayi1.text()) - int(self.ui.txt_sayi2.text()) elif sender == 'Carpma': result = int(self.ui.txt_sayi1.text()) * int(self.ui.txt_sayi2.text()) elif sender == 'Bolme': result = int(self.ui.txt_sayi1.text()) / int(self.ui.txt_sayi2.text()) self.ui.lbl_sonuc.setText('sonuç: '+ str(result))
class MainWindow_EXEC(): def __init__(self): app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(MainWindow) self.update_tree() self.update_calendar() self.update_progressbar() MainWindow.show() sys.exit(app.exec_()) #---------------------------------------------------------- def update_tree(self): # self.print_tree() self.ui.treeWidget.headerItem().setText(1, 'Header 2') self.ui.treeWidget.topLevelItem(0).setText(1, "Item 2") self.ui.treeWidget.topLevelItem(0).addChild( QtWidgets.QTreeWidgetItem()) self.ui.treeWidget.topLevelItem(0).child(0).setText(1, "Subitem 2") # self.print_tree() # print(self.ui.treeWidget.topLevelItem(0).text(1)) # print(self.ui.treeWidget.topLevelItem(0).text(0)) # print(self.ui.treeWidget.topLevelItem(0).child(0).text(0)) # print(self.ui.treeWidget.topLevelItem(0).child(0).text(1)) def print_tree(self): header0 = self.ui.treeWidget.headerItem().text(0) header1 = self.ui.treeWidget.headerItem().text(1) print(header0 + '\n' + header1 + '\n') #---------------------------------------------------------- def update_calendar(self): self.ui.calendarWidget.selectionChanged.connect(self.update_date) def update_date(self): self.ui.dateEdit.setDate(self.ui.calendarWidget.selectedDate()) #---------------------------------------------------------- def update_progressbar(self): radio_3 = self.ui.radioButton_3.text() self.ui.radioButton_3.setText('Set Progressbar') radio_3_upd = self.ui.radioButton_3.text() print(radio_3, radio_3_upd) self.ui.radioButton_3.clicked.connect(self.set_progressbar) def set_progressbar(self): progress_value = self.ui.progressBar.value() print('progressBar: ', progress_value) new_value = self.ui.lcdNumber.value() self.ui.progressBar.setValue(new_value) print('progressBar: ', self.ui.progressBar.value())
def setupUi(self, MainWindow): global version Ui_MainWindow.setupUi(self, MainWindow) MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "qupac "+version, None, QtGui.QApplication.UnicodeUTF8)) self.connect(self.searchField,QtCore.SIGNAL("cursorPositionChanged(int,int)"),self.search) self.connect(self.searchField,QtCore.SIGNAL("returnPressed()"),self.searchAur) self.connect(self.searchButton,QtCore.SIGNAL("pressed()"),self.searchAur) self.connect(self.installButton,QtCore.SIGNAL("pressed()"),self.doInstall) self.oldSearchString=""
class MainWindow(QtGui.QMainWindow): def __init__(self, ip, port=8080, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.ipAddress.setText(ip) self.ui.proxyPort.setValue(port) self.ui.startProxy.clicked.connect(self.startStopProxy) self.ui.actionQuit.triggered.connect(self.quit) self.ui.actionAbout.triggered.connect(self.about) self.ui.actionOpen_PCAP.triggered.connect(self.openPCAP) self.proxy = None def quit(self): if self.proxy: self.proxy.terminate() self.proxy = None self.close() def about(self): QtGui.QMessageBox.about( self, "About", "SWProxy: Summoners War Proxy Tool\nWritten by KaKaRoTo\n\nLicensed under LGPLv3 and available at : \n\thttps://github.com/kakaroto/SWParser\n" ) def openPCAP(self): pcap_file = QtGui.QFileDialog.getOpenFileName() SWProxy.parse_pcap(pcap_file) def log(self, str): self.ui.logWindow.addItem(str) def startStopProxy(self): self.ui.proxyPort.setReadOnly(True) self.ui.proxyPort.setEnabled(False) self.ui.ipAddress.setReadOnly(True) self.ui.ipAddress.setEnabled(False) if self.proxy: self.ui.startProxy.setText("Start Proxy Server") self.ui.startProxy.setEnabled(False) self.proxy.terminate() else: self.ui.startProxy.setText("Stop Proxy Server") self.proxy = ProxyThread(self.ui.ipAddress.text(), self.ui.proxyPort.value(), parent=self) self.proxy.finished.connect(self.proxyStopped) self.proxy.start() def proxyStopped(self): self.proxy = None self.ui.ipAddress.setReadOnly(False) self.ui.ipAddress.setEnabled(True) self.ui.proxyPort.setReadOnly(False) self.ui.proxyPort.setEnabled(True) self.ui.startProxy.setEnabled(True)
class Window(QMainWindow): def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.connectButton.clicked.connect(self.printValue()) def printValue(self): print(self.ui.serverIp.text())
class myApp(QtWidgets.QMainWindow): def __init__(self): super(myApp, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.btn_send.clicked.connect(self.download) def download(self): advertisementID = self.ui.txt_advertisementID.text() sahibinden = Sahibinden(advertisementID) sahibinden.goAdvertisement() myApp.close()
class MainWindow(QtGui.QMainWindow): def __init__(self, ip, port=8080, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.ipAddress.setText(ip) self.ui.proxyPort.setValue(port) self.ui.startProxy.clicked.connect(self.startStopProxy) self.ui.actionQuit.triggered.connect(self.quit) self.ui.actionAbout.triggered.connect(self.about) self.ui.actionOpen_PCAP.triggered.connect(self.openPCAP) self.proxy = None def quit(self): if self.proxy: self.proxy.terminate() self.proxy = None self.close() def about(self): QtGui.QMessageBox.about(self, "About", "SWProxy: Summoners War Proxy Tool\nWritten by KaKaRoTo\n\nLicensed under LGPLv3 and available at : \n\thttps://github.com/kakaroto/SWParser\n") def openPCAP(self): pcap_file = QtGui.QFileDialog.getOpenFileName() SWProxy.parse_pcap(pcap_file) def log(self, str): self.ui.logWindow.addItem(str) def startStopProxy(self): self.ui.proxyPort.setReadOnly(True) self.ui.proxyPort.setEnabled(False) self.ui.ipAddress.setReadOnly(True) self.ui.ipAddress.setEnabled(False) if self.proxy: self.ui.startProxy.setText("Start Proxy Server") self.ui.startProxy.setEnabled(False) self.proxy.terminate() else: self.ui.startProxy.setText("Stop Proxy Server") self.proxy = ProxyThread(self.ui.ipAddress.text(), self.ui.proxyPort.value(), parent=self) self.proxy.finished.connect(self.proxyStopped) self.proxy.start() def proxyStopped(self): self.proxy = None self.ui.ipAddress.setReadOnly(False) self.ui.ipAddress.setEnabled(True) self.ui.proxyPort.setReadOnly(False) self.ui.proxyPort.setEnabled(True) self.ui.startProxy.setEnabled(True)
def setupUi(self, Window): Ui_MainWindow.setupUi(self,Window) Window.refresh.connect(self.do_refresh) self.Window = Window self.deviceList.setModel(self.lm) self.deviceList.selectionModel().currentChanged.connect(self.cfgStatusUpdate) self.cfgButton.clicked.connect(self.configure) self.actionConfigure.activated.connect(self.configure) self.do_refresh() self.monitor = pyudev.Monitor.from_netlink(ctx) self.monitor.filter_by(subsystem='usb') self.observer = QUDevMonitorObserver(self.monitor) self.observer.deviceAdded.connect(self.do_refresh) self.observer.deviceRemoved.connect(self.do_refresh) self.monitor.start()
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self, *args, obj=None, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pushButton.clicked.connect( QtWidgets.QApplication.instance().quit) self.ui.PushButton.clicked.connect(self.clickMethod) def clickMethod(self): SourceCode.source_code(self.ui.lineEdit.text(), self.ui.lineEdit_2.text()) #print(self.ui.lineEdit.text()+"\n"+self.ui.lineEdit_2.text()) self.ui.lineEdit.setText("") self.ui.lineEdit_2.setText("")
class MyMainW(QtGui.QMainWindow): DB = None def __init__(self, db, parent=None): MyMainW.DB = db QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.lineEdit.setText( time.strftime('%Y-%m-%d ', time.localtime(time.time()))) str = "Welcome! Happy Every Day!" self.ui.textEdit.setText(str) QtCore.QObject.connect(self.ui.action_2, QtCore.SIGNAL("triggered()"), self.openBookInfo) QtCore.QObject.connect(self.ui.action_3, QtCore.SIGNAL("triggered()"), self.openSupplierInfo) QtCore.QObject.connect(self.ui.action_4, QtCore.SIGNAL("triggered()"), self.openCusInfo) QtCore.QObject.connect(self.ui.action_5, QtCore.SIGNAL("triggered()"), self.openAddBookInfo) QtCore.QObject.connect(self.ui.action_6, QtCore.SIGNAL("triggered()"), self.openStockInfo) QtCore.QObject.connect(self.ui.action_7, QtCore.SIGNAL("triggered()"), self.openAboutInfo) def openAboutInfo(self): message = QtGui.QMessageBox(self) message.setText("version:2.0\nCopyright (c) 2012 Lv Kaiyang") message.exec_() def openStockInfo(self): MyStockInfo(MyMainW.DB, self).show() def openAddBookInfo(self): row = [] MyAABook(MyMainW.DB, self, row).show() def openBookInfo(self): MyBookInfo(MyMainW.DB, self).show() def openSupplierInfo(self): MySupplierInfo(MyMainW.DB, self).show() def openCusInfo(self): MyCusInfo(MyMainW.DB, self).show()
class MainDialog(QtGui.QDialog): def __init__(self, parent=None): # RSA self.rsa = RSA() QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.btnGenerate.clicked.connect(self.generateKeys) self.ui.btnEncMessage.clicked.connect(self.createEncryptMsgDialog) self.ui.btnEncFile.clicked.connect(self.createEncryptFileDialog) self.generateKeys() self.ui.textPublicKey_n.textChanged.connect(self.onPublicKeyChanged) self.ui.textPublicKey_e.textChanged.connect(self.onPublicKeyChanged) self.ui.textPrivateKey.textChanged.connect(self.onPrivateKeyChanged) def generateKeys(self): self.rsa.genKeys() n,e = self.rsa.getPublicKey() self.ui.textPublicKey_n.setText(str(n)) self.ui.textPublicKey_e.setText(str(e)) self.ui.textPrivateKey.setText(str(self.rsa.getPrivateKey())) def createEncryptMsgDialog(self): encryptDialog = EncryptDialog(self.rsa, self) encryptDialog.show() def createEncryptFileDialog(self): encryptFileDialog = EncryptFileDialog(self.rsa, self) encryptFileDialog.show() def onPublicKeyChanged(self): try: n = int(self.ui.textPublicKey_n.toPlainText()) e = int(self.ui.textPublicKey_e.toPlainText()) self.rsa.setPublicKey(n, e) except: print('Error.') def onPrivateKeyChanged(self): try: d = int(self.ui.textPrivateKey.toPlainText()) self.rsa.setPrivateKey(d) except: print('Invalid Key')
class GUI(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.video = Video(cv2.VideoCapture(0)) self._timer = QTimer(self) self._timer.timeout.connect(self.play) self._timer.start(24) self.update() self.ui.btnCapture.clicked.connect(self.cb) self.ui.btnAddText.clicked.connect(self.addText) self.ret, self.captureFrame = self.video.capture.read() def cb(self): self.video.captureNextFrame() frame = self.video.convertFrame() self.ui.videoFrame_2.setPixmap(frame) self.ui.videoFrame_2.setScaledContents(True) self.captureFrame = self.video.captureFrame() cv2.imwrite("picture/test.jpg", self.captureFrame) print 'Captured' def addText(self): imText = self.video.getImage() imOrg = self.video.getImage() text = "%s" % self.ui.TextFieldAddText.text() cv2.putText(imText, text, (20, 450), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) cv2.imwrite("picture/testText.jpg", imText) pixmap = QPixmap('picture/testText.jpg') self.ui.videoFrame_2.setPixmap(pixmap) print 'Text added' + text def play(self): try: self.video.captureNextFrame() self.ui.videoFrame.setPixmap(self.video.convertFrame()) self.ui.videoFrame.setScaledContents(True) except TypeError: print "No Frame" print "No Frame"
class MainDialog(QtGui.QDialog): def __init__(self, parent=None): # RSA self.rsa = RSA() QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.btnGenerate.clicked.connect(self.generateKeys) self.ui.btnEncMessage.clicked.connect(self.createEncryptMsgDialog) self.ui.btnEncFile.clicked.connect(self.createEncryptFileDialog) self.generateKeys() self.ui.textPublicKey_n.textChanged.connect(self.onPublicKeyChanged) self.ui.textPublicKey_e.textChanged.connect(self.onPublicKeyChanged) self.ui.textPrivateKey.textChanged.connect(self.onPrivateKeyChanged) def generateKeys(self): self.rsa.genKeys() n, e = self.rsa.getPublicKey() self.ui.textPublicKey_n.setText(str(n)) self.ui.textPublicKey_e.setText(str(e)) self.ui.textPrivateKey.setText(str(self.rsa.getPrivateKey())) def createEncryptMsgDialog(self): encryptDialog = EncryptDialog(self.rsa, self) encryptDialog.show() def createEncryptFileDialog(self): encryptFileDialog = EncryptFileDialog(self.rsa, self) encryptFileDialog.show() def onPublicKeyChanged(self): try: n = int(self.ui.textPublicKey_n.toPlainText()) e = int(self.ui.textPublicKey_e.toPlainText()) self.rsa.setPublicKey(n, e) except: print('Error.') def onPrivateKeyChanged(self): try: d = int(self.ui.textPrivateKey.toPlainText()) self.rsa.setPrivateKey(d) except: print('Invalid Key')
class Application(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.UI = Ui_MainWindow() self.setupUI() self.setWindowIcon(QtGui.QIcon("Icon/icon_app.png")) screen = QtWidgets.QDesktopWidget().screenGeometry() self.setGeometry(0,0,screen.width(), screen.height()) def setupUI(self): self.UI.setupUi(self) self.UI.editUsername.setFocus() self.UI.menuBar.setVisible(False) def onDestroy(self): self.destroy() sys.exit(app.exec_())
def MainWindow_Run(): if __name__ == "__main__": app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QDialog() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() result = MainWindow.exec_() if result: #print(ui.hola) #MainWindow.close() #sys.exit(app.exec_()) QMessageBox.information( None, u"Información", 'Se completo con exito, el modo elejido es: ' + ui.modo) return 0
class App(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) #Add OpenGL widget to main window self.gl_widget = GLWidget(self) self.ui.main_layout.addWidget(self.gl_widget) #Connect gui controls to model self.ui.zoom_slider.valueChanged.connect(self.gl_widget.zoom) self.ui.elevation_slider.valueChanged.connect(self.gl_widget.elevation) self.ui.azimuth_slider.valueChanged.connect(self.gl_widget.azimuth) self.ui.wireframe_check.toggled.connect(self.gl_widget.wire) self.ui.axes_check.toggled.connect(self.gl_widget.show_axes) self.ui.perspective_check.toggled.connect(self.gl_widget.set_projection)
class UIControl(QtWidgets.QMainWindow): def __init__(self, parent=None): super(UIControl, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.OptionViewFrame.OVHookCollectionButton.clicked.connect( lambda: self.changeView(0)) self.ui.OptionViewFrame.OVHookButton.clicked.connect( lambda: self.changeView(1)) self.ui.OptionViewFrame.OVLivePacketButton.clicked.connect( lambda: self.changeView(2)) self.ui.OptionViewFrame.OVPacketPCAPButton.clicked.connect( lambda: self.changeView(3)) self.ui.HookCollectionViewPage.HCVAddHookButton.clicked.connect( lambda: self.showAddHookCollectionOverlay()) self.ui.HookViewPage.HVAddHookButton.clicked.connect( lambda: self.showAddHooknOverlay()) self.ui.HookViewPage.HVDeleteHookButton.clicked.connect( lambda: self.deleteHook()) def changeView(self, index): self.ui.ContentViewWidget.setCurrentIndex(index) def showAddHooknOverlay(self): dialog = Ui_CreatEditHookOverlay() if dialog.exec_() == QDialog.Accepted: result = dialog.result # Send result to Hook Handler, depending of the repsonse add to page # self.ui.HookViewPage.addHook(result[0], result[1], "0") def deleteHook(self): hookToDelete = self.ui.HookViewPage.selectedHook() # Alert Hook Handler and pass it hookToDlete # self.ui.HookViewPage.deleteHook() def showAddHookCollectionOverlay(self): dialog = QtWidgets.QDialog() overlay = EditHookCollectionOverlay.Ui_CreatEditHookCollectionOverlay() overlay.setupUi(dialog) dialog.exec_() dialog.show()
class MyWin(QtWidgets.QMainWindow): def __init__(self, parent=None): super(MyWin, self).__init__() self.ExpertMode = None self.Diagnostics = None self.ui = Ui_MainWindow() self.ui.setupUi(self) #Подключение клика к кнопкам self.ui.buttonExpertMode.clicked.connect(self.openExpertMode) self.ui.buttonResult.clicked.connect(self.openDiagnostics) def openExpertMode(self): if not self.ExpertMode: self.ExpertMode = ExpertMode(self) self.ExpertMode.refresh() self.ExpertMode.show() def openDiagnostics(self): if not self.Diagnostics: self.Diagnostics = Diagnostics(self) self.Diagnostics.show()
class myWindow(QtWidgets.QMainWindow): def __init__(self): super(myWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.tree = BinaryTree() self.scene = QtWidgets.QGraphicsScene() self.ui.graphicsView.setScene(self.scene) self.scale = 0.8 self.ui.graphicsView.scale(self.scale, self.scale) self.ui.pushButton.clicked.connect(self.AddEl) self.ui.pushButton_2.clicked.connect(self.DelEl) self.ui.pushButton_4.clicked.connect(self.Clear) self.ui.pushButton_5.clicked.connect(self.Generate) def AddEl(self): self.tree.AddNode(int(self.ui.spinBox.text())) self.scene.clear() self.PaintT() def DelEl(self): self.tree.DeleteNode(int(self.ui.spinBox_2.text())) self.scene.clear() self.PaintT() def Clear(self): self.scene.clear() self.tree.Clear() self.PaintT() def Generate(self): self.scene.clear() self.tree.GenerateTree() self.PaintT() def PaintT(self): self.ui.label_5.setText(str(self.tree.count)) self.ui.label_7.setText(str(self.tree.lvlCount)) self.tree.paint(self.scene, self.scale, self.tree.root)
class myApp(QtWidgets.QMainWindow): def __init__(self): super(myApp, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.btn_topla.clicked.connect(self.Hesapla) self.ui.btn_cikar.clicked.connect(self.Hesapla) self.ui.btn_carp.clicked.connect(self.Hesapla) self.ui.btn_bol.clicked.connect(self.Hesapla) def Hesapla(self): sender = self.sender() print(sender.text()) result = 0 if sender.text() == 'Toplam': result = float(self.ui.txt_sayi1.text()) + float( self.ui.txt_sayi2.text()) print(result) self.ui.sonuc_lbl.setText(f'Sonuç: {str(result)}') elif sender.text() == 'Çıkarma': result = float(self.ui.txt_sayi1.text()) - float( self.ui.txt_sayi2.text()) print(result) self.ui.sonuc_lbl.setText(f'Sonuç: {str(result)}') elif sender.text() == 'Çarpma': result = float(self.ui.txt_sayi1.text()) * float( self.ui.txt_sayi2.text()) print(result) self.ui.sonuc_lbl.setText(f'Sonuç: {str(result)}') elif sender.text() == 'Bölme': result = float(self.ui.txt_sayi1.text()) / float( self.ui.txt_sayi2.text()) print(result) self.ui.sonuc_lbl.setText(f'Sonuç: {str(result)}') else: pass
class AppWindow(QMainWindow): def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) centralWidget = QWidget() #centralWidget.resize(200,300) layout = QVBoxLayout() hbox = QHBoxLayout() hbox.addLayout(layout) #hbox.addStretch(1) anotherwidget = CategoryNewWindow() hbox.addWidget(anotherwidget) centralWidget.setLayout(hbox) self.setCentralWidget(centralWidget) sql = 'SELECT *FROM Categories LIMIT 0,2' result = conn.execute(sql) i=20; for row in result: l = LinkLabel() l.linkId=row[0] l.setText(row[1]) l.setGeometry(QtCore.QRect(150, i, 200, 20)) anotherwidget.make_connection(l) i=i+20 layout.addWidget(l) self.show() def showNewCategory(self,conn): # self.hide() self.catNew = CategoryNewWindow() self.catNew.show() def showListCategory(self): self.catList = CategoryListWindow() self.catList.show()
class MainAppWindow(QMainWindow): def __init__(self): try: super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) load_data_into_table(self) self.ui.pbAdd.clicked.connect(lambda: show_add_processes_gui(self)) self.ui.pbDebug.clicked.connect(lambda: show_debug_gui(self)) self.ui.tableWidget.cellChanged.connect(lambda: update_db(self)) self.ui.tableWidget.itemSelectionChanged.connect( lambda: selection_changed(self)) self.ui.pbRemove.clicked.connect(lambda: remove_data(self)) if C.DEBUG: self.ui.pbDebug.setVisible(True) else: self.ui.pbDebug.setVisible(False) self.show() except Exception as ex: print_exception(ex)
class GroundSystem(QtGui.QMainWindow): # # Init the class # def __init__(self, parent=None): QtGui.QMainWindow.__init__(self) # Init lists self.ipAddressesList = ['All'] self.spacecraftNames = ['All'] # Init GUI and set callback methods for buttons self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pushButtonStartTlm.clicked.connect(self.startTlmSystem) self.ui.pushButtonStartCmd.clicked.connect(self.startCmdSystem) def closeEvent(self, evnt): if self.RoutingService: self.RoutingService.stop() print "Stopped routing service" super(GroundSystem, self).closeEvent(evnt) # Read the selected spacecraft from combo box on GUI def getSelectedSpacecraftAddress(self): return str(self.ui.comboBoxIpAddresses.currentText()) # Returns the name of the selected spacecraft def getSelectedSpacecraftName(self): return self.spacecraftNames[self.ipAddressesList.index(self.getSelectedSpacecraftAddress())] # # Display popup with error # def DisplayErrorMessage(self, message): print message alert = QtGui.QMessageBox() alert.setText(message) alert.setIcon(QtGui.QMessageBox.Warning) alert.exec_() # Start the telemetry system for the selected spacecraft def startTlmSystem(self): selectedSpacecraft = self.getSelectedSpacecraftName() # Setup the subscription (to let know the telemetry system the messages it will be receiving) if selectedSpacecraft == 'All': subscription = '--sub=GroundSystem' else: subscription = '--sub=GroundSystem.' + selectedSpacecraft + '.TelemetryPackets' # Open Telemetry System system_call = '( cd Subsystems/tlmGUI/ && python TelemetrySystem.py ' + subscription + ' ) & ' os.system(system_call) # Start command system def startCmdSystem(self): os.system('( cd Subsystems/cmdGui/ && python CommandSystem.py ) & ') # Start FDL-FUL gui system #def startFDLSystem(self): # selectedSpacecraft = self.getSelectedSpacecraftName() # if selectedSpacecraft == 'All': # subscription = '' # self.DisplayErrorMessage('Cannot open FDL manager.\nNo spacecraft selected.') # else: # subscription = '--sub=GroundSystem.' + selectedSpacecraft # os.system('( cd Subsystems/fdlGui/ && python FdlSystem.py ' + subscription + ' ) & ') # Update the combo box list in gui def updateIpList(self, ip, name): self.ipAddressesList.append(ip) self.spacecraftNames.append(name) self.ui.comboBoxIpAddresses.addItem(ip) # Start the routing service (see RoutingService.py) def initRoutingService(self): self.RoutingService = RoutingService(self) self.connect(self.RoutingService, self.RoutingService.signalUpdateIpList, self.updateIpList) self.RoutingService.start()
class GoogleImagesDownloader(QtGui.QMainWindow): def __init__(self, parent=None): super(GoogleImagesDownloader, self).__init__(parent) self.webDriverUtils = WebDriverUtils() self.downloadUtils = DownloadUtils() self.save_dir = os.getcwd() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.delete_button.clicked.connect(self.delete_on_click) self.ui.save_button.clicked.connect(self.save_on_click) self.ui.next_image_button.clicked.connect(self.next_image_on_click) self.ui.previous_image_button.clicked.connect(self.previous_image_on_click) self.ui.search_button.clicked.connect(self.search_on_click) self.ui.save_dir_button.clicked.connect(self.save_dir_on_click) self.add_action('d', self.next_image_on_click) self.add_action('a', self.previous_image_on_click) self.add_action('s', self.save_on_click) def closeEvent(self, event): print('On_close') self.webDriverUtils.close() def add_action(self, shortcut, method_name): action = QtGui.QAction(self) action.setShortcut(shortcut) action.setShortcutContext(QtCore.Qt.ApplicationShortcut) self.addAction(action) QtCore.QObject.connect(action, QtCore.SIGNAL("triggered()"), method_name) def next_image_on_click(self): print('Next Image') raw_image = self.downloadUtils.get_next_image() while not raw_image: raw_image = self.downloadUtils.get_next_image() self.update_image_view(raw_image) self.update_current_image_index_label() def previous_image_on_click(self): print('Previous Image') raw_image = self.downloadUtils.get_previous_image() self.update_image_view(raw_image) self.update_current_image_index_label() def update_image_view(self, raw_image): qimage = ImageQt(Image.open(io.BytesIO(raw_image))) pixmap = QtGui.QPixmap.fromImage(qimage).scaled(800, 800, aspectRatioMode=QtCore.Qt.KeepAspectRatio, transformMode=QtCore.Qt.SmoothTransformation) self.ui.image_view.setPixmap(pixmap) def save_on_click(self): print('Saving Image...') saved_filename = self.downloadUtils.save_current_image(self.save_dir) self.update_saved_images_count_label() def delete_on_click(self): print('Deleting Image...') self.downloadUtils.delete_current_image() self.update_saved_images_count_label() def update_saved_images_count_label(self): count = self.downloadUtils.get_saved_images_count() self.ui.saved_images_count_label.setText(count) def search_on_click(self): print('Searching') search_text = self.ui.search_term_text_box.text().strip() new_images_list = self.webDriverUtils.get_image_urls_from_google_images(search_text) for url, _ in new_images_list: self.ui.loaded_url.addItem(str(url)) self.downloadUtils.update_url_list(new_images_list) self.update_current_image_index_label() print(search_text) def update_current_image_index_label(self): count = self.downloadUtils.get_url_count() current_index = self.downloadUtils.get_current_image_index() self.ui.current_image_index_label.setText(str(count)+' \ '+str(current_index)) def save_dir_on_click(self): print('changing save dir') open_dir = QtGui.QFileDialog.getExistingDirectory(self, "Open Directory", self.save_dir, QtGui.QFileDialog.ShowDirsOnly | QtGui.QFileDialog.DontResolveSymlinks).strip() print(open_dir) if not open_dir == 0: print('New Folder : ' + open_dir) self.save_dir = open_dir
class Nexus(QMainWindow): """ Die Hauptklasse des Programms. In dieser Klasse wird die GUI gesteuert und die Würfelwürfe aufgerufen. """ dicePoolChanged = pyqtSignal(int) xAgainChanged = pyqtSignal(int) cursed = pyqtSignal(bool) def __init__(self, parent=None): """ Konstruktor """ self.translator_app = QTranslator() self.translator_qt = QTranslator() QApplication.installTranslator( self.translator_app ) QApplication.installTranslator( self.translator_qt ) QWidget.__init__(self, parent) QCoreApplication.setOrganizationName("Caern") QCoreApplication.setOrganizationDomain("www.caern.de") QCoreApplication.setApplicationName("DiceRoller WoD") QCoreApplication.setApplicationVersion(QString.number(PROGRAM_VERSION_MAJOR) + "." + QString.number(PROGRAM_VERSION_MINOR) + "." + QString.number(PROGRAM_VERSION_CHANGE) ) QApplication.setWindowIcon(QIcon(":/icons/logo/WoD.png")) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.createInfo() #self.createLanguageMenu() self.instantRoll = InstantRoll() self.extendedRoll = ExtendedRoll() # Dieser Zähler bestimmt, wie der rollende Würfel angezeigt wird. self.timerDice = QTimer() # Verzögert die tatsächliche Ausführung des Würfelwurfs. self.timerRoll = QTimer() self.populateUi() self.createConnections() self.initializing() self.setWindowTitle(QCoreApplication.applicationName()) #self.retranslateUi() ## Die von der letzten Benutzung gespeicherte Größe und Position auf dem Bildschirm laden. #self.readSettings() #def closeEvent(self, event): #""" #Diese Funktion wird aufgerufen, wann immer das Programm geschlossen wird. #Die Idee dahinter ist, vor dem Beenden, Größe und Position des Fensters zu speichern. #""" #self.writeSettings() #event.accept() def createInfo(self): """ Erzeugt Tooltips und Hilfe für die einzelnen Teile des Programms. """ self.ui.action_houserules.setStatusTip(self.ui.action_houserules.toolTip()) #def createLanguageMenu(self): #""" #Erzeugt das Menü zum Umschalten zwischen den möglichen Sprachen. #""" #self.menu_language = QMenu( self.tr("&Language") ) #self.actionGroup_language = QActionGroup(self) #self.langPath = getPath() + "/" + PROGRAM_LANGUAGE_PATH #self.dir_qm = QDir( self.langPath ); #self.fileNames = self.dir_qm.entryList( QStringList( "DiceRoller-WoD_*.qm" )); ## Englisch hat keine qm-Datei, also muß es von Hand hinzugefügt werden. #self.action = QAction( "&1 English", self.actionGroup_language ) #self.action.setCheckable( True ) #self.action.setData( "en" ) #self.action.setChecked( True ) #self.menu_language.addAction( self.action ) #self.actionGroup_language.addAction( self.action ) #iter = 0 #for i in self.fileNames: #self.trFilename = unicode(i) #self.locale = unicode(i) #self.locale = self.locale[(self.locale.find( "_" )+1):(self.locale.find( "." ))] #self.translator = QTranslator() #self.translator.load( self.trFilename, self.dir_qm.absolutePath() ) #self.language = self.translator.translate( "MainWindow", "English" ) #self.action = QAction( "&" + QString.number(iter + 2) + " " + self.language, self.actionGroup_language ) #self.action.setCheckable( True ) #self.action.setData( self.locale ) #self.menu_language.addAction ( self.action ) #self.actionGroup_language.addAction ( self.action ) #iter += 1 #self.actionGroup_language.triggered.connect(self.switchLanguage) #self.ui.menuBar.insertMenu(self.ui.menuHelp.menuAction(), self.menu_language) #def switchLanguage( self, action ): #""" #Schaltet zwischen den einzelnen Sprachen um. #""" #self.locale = action.data().toString(); #self.qmPath = getPath() + "/" + PROGRAM_LANGUAGE_PATH ##if self.translator_app.load( "DiceRoller-WoD_" + self.locale, self.qmPath ): ##qDebug("Hat DiceRoller-WoD_" + self.locale + " geladen.") ##if self.translator_qt.load( "qt_" + self.locale, QLibraryInfo.location ( QLibraryInfo.TranslationsPath ) ): ##qDebug("Hat qt_" + self.locale + " geladen.") ## Alle Texte neu setzen #self.retranslateUi() ## Seltsamerweise ist retranslate in Ui_MainWindow leer. Ich weiß nicht, wieso das der Fall ist. #self.ui.retranslateUi(self.ui) #def retranslateUi(self): #""" #Diese Funktion übersetzt alle Texte, welche nicht in der .ui-Datei festgelegt sind, sondern im Quellcode (hier) geschrieben wurden. #""" #self.menu_language.setTitle( self.tr( "&Language" ) ) #self.reset() def populateUi(self): self.svgRenderer = QSvgRenderer(":/icons/W10.svg") self.scene = QGraphicsScene() self.view = QGraphicsView() self.view.setFrameShape(QFrame.NoFrame) self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.view.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) self.view.setStyleSheet("background-color: transparent;"); self.view.setScene(self.scene) self.ui.horizontalLayout_dice.insertWidget(1, self.view) def createConnections(self): """ Erstelle die Verbindungen zwischen den verschiedenen Klassen und Elementen des Programms. """ self.ui.action_about.triggered.connect(self.aboutApp) self.ui.action_aboutQt.triggered.connect(QApplication.aboutQt) self.ui.action_houserules.toggled.connect(self.setHouserules) self.ui.pushButton_roll.clicked.connect(self.roll) self.ui.spinBox_pool.valueChanged.connect(self.calcDicePool) self.ui.spinBox_pool.valueChanged.connect(self.reset) self.ui.spinBox_modifier.valueChanged.connect(self.calcDicePoolMod) self.ui.spinBox_modifier.valueChanged.connect(self.reset) self.ui.checkBox_rote.toggled.connect(self.instantRoll.setRote) self.ui.checkBox_rote.toggled.connect(self.extendedRoll.setRote) self.ui.checkBox_rote.toggled.connect(self.reset) self.ui.comboBox_xAgain.activated.connect(self.setXAgainThreshold) self.ui.comboBox_xAgain.activated.connect(self.reset) self.ui.groupBox_extended.toggled.connect(self.changeText) self.ui.radioButton_target.toggled.connect(self.changeText) self.ui.radioButton_maxRolls.toggled.connect(self.changeText) self.ui.groupBox_extended.toggled.connect(self.reset) self.ui.radioButton_target.toggled.connect(self.setExtendedMode) self.ui.spinBox_target.valueChanged.connect(self.extendedRoll.setTarget) self.ui.spinBox_target.valueChanged.connect(self.reset) self.ui.spinBox_maxRolls.valueChanged.connect(self.extendedRoll.setMaxRolls) self.ui.spinBox_maxRolls.valueChanged.connect(self.reset) self.ui.checkBox_rollsLimited.toggled.connect(self.extendedRoll.setLimited) self.ui.checkBox_rollsLimited.toggled.connect(self.reset) self.xAgainChanged.connect(self.instantRoll.setThreshold) self.xAgainChanged.connect(self.extendedRoll.setThreshold) self.cursed.connect(self.instantRoll.setCurse) self.cursed.connect(self.extendedRoll.setCurse) self.instantRoll.rolled.connect(self.setResultSuccesses) self.extendedRoll.rolled.connect(self.setResultSuccesses) self.extendedRoll.rollsNeeded.connect(self.setResultRolls) self.instantRoll.rollFinished.connect(self.setResult) self.extendedRoll.rollFinished.connect(self.setResult) self.dicePoolChanged.connect(self.changeDiceDisplay) self.timerDice.timeout.connect(self.displayDice) self.timerRoll.timeout.connect(self._executeRoll) def initializing(self): """ Initialisiert das Programm mit den Startwerten. """ self.ui.action_quit.setIcon(QIcon(":/icons/actions/exit.png")) self.ui.action_about.setIcon(QIcon(":/icons/logo/WoD.png")) self.ui.pushButton_quit.setIcon(self.ui.action_quit.icon()) self.ui.pushButton_roll.setIcon(QIcon(":icons/W10_0.svg")) self.ui.action_quit.setMenuRole(QAction.QuitRole) self.ui.action_about.setText(self.tr("About %1...").arg(QApplication.applicationName())) self.ui.action_about.setMenuRole(QAction.AboutRole) self.ui.spinBox_pool.setValue(2) self.ui.checkBox_rote.setChecked(False) self.ui.comboBox_xAgain.setCurrentIndex(0) self.ui.spinBox_target.setValue(1) self.changeText() self.ui.radioButton_target.setChecked(True) self.ui.groupBox_extended.setChecked(False) self.ui.checkBox_rollsLimited.setChecked(True) self.dice = [] for i in xrange(10): self.W10_x = QGraphicsSvgItem() self.W10_x.setSharedRenderer(self.svgRenderer) self.W10_x.setElementId("layer" + str(i)) #self.W10_x.setVisible(False) # Ich lege diese Liste an, da ich auf die Liste in self.scene irgendwie nicht zugreifen kann. self.dice.append(self.W10_x) #self.scene.addItem(self.W10_x) def displayDice(self, value=None): """ @todo Der Würfel kann mehrmals in Folge das selbe Ergebnis anzeigen, was dazu führt, daß der Bildablauf zu stocken scheint. """ if (value == None): dieValue = Random.random(10)-1 else: dieValue = value for item in self.scene.items(): self.scene.removeItem(item) self.scene.addItem(self.dice[dieValue]) self.view.setSceneRect(self.scene.itemsBoundingRect()) self.view.fitInView(self.dice[dieValue]) def changeDiceDisplay(self, number): """ Diese Funktion bestimmt, wieviele Würfel angezeigt werden. """ pass #if (self.ui.horizontalLayout_dice.count > 2): #pass #randomValue = Random.random(10)-1 #for die in xrange(number): #self.__W10_scene = QGraphicsScene() #self.__W10_scene.addItem(self.dice[randomValue]) #self.__W10_view = QGraphicsView() #self.__W10_view.setScene(self.__W10_scene) #self.__W10_view.setSceneRect(self.scene.itemsBoundingRect()) #self.__W10_view.fitInView(self.dice[randomValue]) #self.ui.horizontalLayout_dice.insertWidget(1, self.__W10_view) def aboutApp(self): """ Zeigt die Info-Nachricht an. """ self.appText = self.tr(""" <h1>%1</h1> <h2>Version: %2</h2> <p>Copyright (C) 2011 by Victor von Rhein<br> EMail: [email protected]</p> """).arg(QCoreApplication.applicationName()).arg(QCoreApplication.applicationVersion()) self.gnuText = self.tr(""" <h2>GNU General Public License</h2> <p>This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.</p> <p>This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.</p> <p>You should have received a copy of the GNU General Public License along with this program. If not, see <a>http://www.gnu.org/licenses/</a>.</p> """) self.wodText = self.tr(""" <h2>%1</h2> <p>%1, %2, the %3 and all referring terms and symbols are copyrighted by %4</p> """).arg("World of Darkness").arg("White Wolf").arg("White Wolf-Logo").arg("White Wolf Inc.") self.aboutText = self.appText + self.gnuText + self.wodText QMessageBox.about(self, "About " + QCoreApplication.applicationName(), self.aboutText ) def roll(self): """ Der Wurf wird durchgeführt. Der tatsächliche Wurf wird aber von den Timern angestoßen. """ # Es wird ein rollender Würfel angezeigt. self.timerDice.start(DICEROLL_TIMER_INTERVAL) self.timerRoll.start(DICEROLL_TIMER_DELAY) def _executeRoll(self): """ Entscheidet vor dem eigentlichen Würfelwurf, ob ein normaler oder ein erweiterter Wurf notwendig ist und führt diesen aus. """ if self.ui.groupBox_extended.isChecked(): #qDebug("Checked") self.extendedRoll.roll() else: #qDebug("Not Checked") self.instantRoll.roll() # Die Anzeige des rollenden Würfels wird angehalten self.timerDice.stop() self.timerRoll.stop() def calcDicePool(self, value): """ Berechnet die Größe des zur Verfügung stehenden Würfelpools, welcher von den Würfeln und den Modifikatoren abhängt. """ self.instantRoll.poolSize = value + self.ui.spinBox_modifier.value() self.extendedRoll.poolSize = self.instantRoll.poolSize self.extendedRoll.limit = value self.dicePoolChanged.emit(self.instantRoll.poolSize) def calcDicePoolMod(self, value): """ Berechnet wie schon calcDicePool() die Größe des Würfelvorrats, allerdings werden dieser Funktion andere Argumente übergeben. """ self.instantRoll.poolSize = value + self.ui.spinBox_pool.value() self.extendedRoll.poolSize = value + self.ui.spinBox_pool.value() def setHouserules(self, value): #qDebug("Test" + str(value)) self.extendedRoll.isHouserules = value def setXAgainThreshold(self, value): """ Legt fest, bei welchem Ergebnis weitergewürfelt werden kann und wann dies überhaupt nicht der Fall sein sollte oder gar Erfolge abgezogen werden können. """ self.__threshold = 0 if (value < 3): self.__threshold = 10 - value # Index 0 entspricht 10 again, 1 entspricht 9 again etc. else: self.__threshold = 11 # Index 3 entspricht "no reroll" self.xAgainChanged.emit(self.__threshold) if (value > 3): self.cursed.emit(True) # Kein reroll und 1er werden Abgezogen. else: self.cursed.emit(False) # 1er werden nicht abgezogen. def setExtendedMode(self, sw): """ Legt den Modus fest, mit welchem der erweiterte Wurf durchgeführt wird. Entweder wird auf ein Ergebnishingewürfelt, oder nach einer bestimmten Anzahl würde die Anzahl der Erfolge gezählt. """ if (sw): self.extendedRoll.isResultInRolls = False else: self.extendedRoll.isResultInRolls = True def setResult(self, value): """ Schreibt das Ergebnis des Wurfs in die GUI. Dabei wird auch je nach Erfolgsqualität bei dem dargestellten Würfel eine andere Augenzahl gezeigt. """ self.ui.statusBar.showMessage(self.tr("Result of diceroll is displayed.")) if (value == DieResult.dramaticFailure): self.ui.label_resultText.setText(self.tr("Dramatic Failure")); self.ui.label_result.setPixmap(QPixmap(":/icons/actions/cnrdelete-all1.png")); self.displayDice(1) elif (value == DieResult.failure): self.ui.label_resultText.setText(self.tr("Failure")); self.ui.label_result.setPixmap(QPixmap(":/icons/actions/fileclose.png")); self.displayDice(Random.random(2, 7)) elif (value == DieResult.success): self.ui.label_resultText.setText(self.tr("Success")); self.ui.label_result.setPixmap(QPixmap(":/icons/actions/ok.png")); self.displayDice(Random.random(8, 9)) else: self.ui.label_resultText.setText(self.tr("Exceptional Success")); self.ui.label_result.setPixmap(QPixmap(":/icons/actions/bookmark.png")); self.displayDice(0) def setResultRolls(self, value): """ Zeigt in der GUI an, wieviele Würfe nötig waren. """ if (self.ui.groupBox_extended.isChecked() and self.ui.radioButton_target.isChecked()): self.ui.lcdNumber_successes.display(value) def setResultSuccesses(self, value): """ Zeigt in der GUI an, wieviele Erfolge erzielt wurden. """ if (not self.ui.groupBox_extended.isChecked() or not self.ui.radioButton_target.isChecked()): self.ui.lcdNumber_successes.display(value) def changeText(self): """ Verändert den Text in der Statuszeile. """ if (self.ui.groupBox_extended.isChecked() and self.ui.radioButton_target.isChecked()): self.ui.label_successes.setText(self.tr("Number of rolls needed:")) else: self.ui.label_successes.setText(self.tr("Number of successes:")) def reset(self): """ Setzt das Programm auf einen definierten Startwert zurück. """ self.ui.label_result.setPixmap(QPixmap(":/icons/actions/fileclose.png")) self.ui.label_resultText.setText(self.tr("No result yet!")) self.ui.lcdNumber_successes.display(0) self.ui.statusBar.showMessage(self.tr("Press the Button to roll the dice!"))
class MainWindowController(QtWidgets.QMainWindow): P = list() N = list() numbers = list() dop_number = int() cluster_works = clusters.ClusterWorks() place_number = PlaceNember.PlaceNumber() get_numbers = Get_numbers_v2.GetNumbers() def __init__(self): super(MainWindowController, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.startPushButton.clicked.connect(self.start_analyse) self.ui.kmeansPushButton.clicked.connect(self.kmeans_clustering) self.ui.graphResultPushButton.clicked.connect(self.graph_result) self.ui.resultTableWidget.resizeColumnsToContents() def clear_table_data(self): for i in range(len(self.P) - 1, -1, -1): self.ui.resultTableWidget.removeRow(i) def set_table_data(self): for i, (p, n, num) in enumerate(zip(self.P, self.N, self.numbers)): self.ui.resultTableWidget.insertRow(i) self.ui.resultTableWidget.setItem( i, 0, QtWidgets.QTableWidgetItem(str(self.dop_number))) self.ui.resultTableWidget.setItem( i, 1, QtWidgets.QTableWidgetItem(str(num))) self.ui.resultTableWidget.setItem( i, 2, QtWidgets.QTableWidgetItem(f'P({p}), N({n})')) def start_analyse(self): self.clear_table_data() del self.P[:] del self.N[:] del self.numbers[:] self.dop_number = self.ui.dopNumberSpinBox.text() self.numbers = self.get_numbers.get_numbers( int(self.ui.countSpinBox.text())) self.P, self.N = self.place_number.get_place_number_list( self.numbers, self.dop_number) self.ui.kmeansPushButton.setEnabled(True) self.ui.graphResultPushButton.setEnabled(True) self.set_table_data() def kmeans_clustering(self): cluster0, cluster1, cluster2, cluster3 = self.cluster_works.clustering( self.numbers, self.dop_number) if cluster0.empty: msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.Warning) msg.setText("Kmeans warning") msg.setInformativeText("Не удалось поделить выборку на 4 кластера") msg.setWindowTitle("Guess Numbers warning") msg.setStandardButtons(QtWidgets.QMessageBox.Ok) msg.exec_() else: self.cluster_works.visualization_clusters(cluster0, cluster1, cluster2, cluster3) def graph_result(self): # numbers_show(self.P, self.N) self.cluster_works.numbers_show(self.numbers, self.dop_number)
class MTuring(QtGui.QMainWindow): def __init__(self): #escencial super(MTuring, self).__init__() #escencial self.ui = Ui_MainWindow() self.ui.setupUi(self)
# Declare/Initialize the python qt ui module import sys from PyQt4.QtGui import QApplication, QMainWindow from MainWindow import Ui_MainWindow from Controller import Controller app = QApplication(sys.argv) window = QMainWindow() ui = Ui_MainWindow() ui.setupUi(window) # Create controller object, and register ui window with it controller = Controller(window, True) # Display the ui window.show() sys.exit(app.exec_())
import sys from PyQt5.QtWidgets import QApplication, QMainWindow from PyQt5 import QtCore, QtWidgets from MainWindow import Ui_MainWindow if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
class StartQT4(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) #Disclaimer dlg=AboutDlg.AbtDlg(self) dlg.exec_() self.CurrentImages=list() self.Mode="Manual"#manual by default self.Iso=[512,384] self.WedgeType=''#Default self.ComplexType=''#Default self.MSEComplexA='None' self.MSEComplexB='None' self.MSENSS='None' self.MSESSS='None' self.MSEPyramid1='None' self.MSEPyramid2='None' self.reportStr='' #Signal-slot connections QtCore.QObject.connect(self.ui.actionNewMachine,QtCore.SIGNAL("triggered()"),self.OpenNewMCDlg) QtCore.QObject.connect(self.ui.actionLoad_ImagesPF0,QtCore.SIGNAL("triggered()"),self.AnalysePicketFence0) QtCore.QObject.connect(self.ui.actionLoad_ImagesPF270,QtCore.SIGNAL("triggered()"),self.AnalysePicketFence270) QtCore.QObject.connect(self.ui.actionLoad_ImagesPF90,QtCore.SIGNAL("triggered()"),self.AnalysePicketFence90) QtCore.QObject.connect(self.ui.actionLoad_ImagesXWedges,QtCore.SIGNAL("triggered()"),self.AnalyseXWedges) QtCore.QObject.connect(self.ui.actionLoad_ImagesYWedges,QtCore.SIGNAL("triggered()"),self.AnalyseYWedges) QtCore.QObject.connect(self.ui.actionLoad_ImagesComplexA,QtCore.SIGNAL("triggered()"),self.AnalyseComplexA) QtCore.QObject.connect(self.ui.actionLoad_ImagesComplexB,QtCore.SIGNAL("triggered()"),self.AnalyseComplexB) QtCore.QObject.connect(self.ui.actionLoad_ImagesPyramid,QtCore.SIGNAL("triggered()"),self.AnalysePyramids) QtCore.QObject.connect(self.ui.actionLoad_ImagesSSS,QtCore.SIGNAL("triggered()"),self.AnalyseSSS) QtCore.QObject.connect(self.ui.actionLoad_ImagesNSS,QtCore.SIGNAL("triggered()"),self.AnalyseNSS) QtCore.QObject.connect(self.ui.actionLoadImages_MLCAlign ,QtCore.SIGNAL("triggered()"),self.AnalyseMLCAlign) QtCore.QObject.connect(self.ui.actionGenerate_report ,QtCore.SIGNAL("triggered()"),self.CreatePDFReport) QtCore.QObject.connect(self.ui.actionAuto_Generate_Report ,QtCore.SIGNAL("triggered()"),self.AutoReport) QtCore.QObject.connect(self.ui.actionAbout,QtCore.SIGNAL("triggered()"),self.ShowAboutDlg) def ShowAboutDlg(self): dlg=AboutDlg.AbtDlg(self) dlg.exec_() def OpenNewMCDlg(self): # dlg=NewMCDlg.newMCDlg(self) # dlg.exec_() pass def SelectMCDlg(self): dlg=NewMCDlg.newMCDlg(self) dlg.exec_() def AnalysePicketFence0(self): if self.Mode=="Manual": files=QFileDialog(self) files.setWindowTitle('Picket Fence 0') self.CurrentImages=files.getOpenFileNames(self,caption='Continuous Stripes (1)') ContStripesDlg1=ContStripesDlg.ContStripesWidget(self) #ContStripesDlg1.Img=DCMReader.ReadDCMFile(str(self.CurrentImages[0])) mypf = PicketFence(str(self.CurrentImages[0])) mypf.image.check_inversion() mypf.analyze(tolerance=0.5, action_tolerance=0.3,hdmlc=False) mypf.save_analyzed_image('PicketFence0',gaurd_rails=True,mlc_peaks=True,overlay=True,leaf_error_subplot=True) #print(mypf.num_pickets,'No. of pickets found') #print(mypf.return_results()) #mypf.plot_analyzed_image() AnalyzedImage=pl.imread('PicketFence0.png') ContStripesDlg1.Stripes.axes.imshow(AnalyzedImage) ContStripesDlg1.ResultsLabel.setText(mypf.return_results()) #mypf.plot_analyzed_image(ContStripesDlg1.Stripes) numPickets=str(mypf.num_pickets) ContStripesDlg1.Stripes.axes.set_title("No. of pickets found: "+numPickets+"Gantry=0") ContStripesDlg1.Stripes.axes.text(5,25,"Tol=0.5mm,Act_Tol=0.3mm",color='g') ContStripesDlg1.Stripes.axes.text(5,60,"Warning:Picket & leaf indexing starts with 0",color='r') self.SaveWidgetScreenShot(ContStripesDlg1,'PicketFence0.jpg') ContStripesDlg1.Stripes.axes.arrow(25,550, 50,0, head_width=10, head_length=25, fc='b', ec='b') ContStripesDlg1.Stripes.axes.arrow(25,550,0,-50, head_width=10, head_length=25, fc='b', ec='b') ContStripesDlg1.Stripes.axes.text(35,570,"Count",color='gray') ContStripesDlg1.Stripes.axes.text(5,515,"Count",color='gray',rotation=90) ContStripesDlg1.Stripes.axes.set_xlabel("Pixel No. G-T") ContStripesDlg1.Stripes.axes.set_ylabel("Pixel No. A-B") if self.Mode=="Manual": ContStripesDlg1.Stripes.draw() ContStripesDlg1.exec_() def AnalysePicketFence270(self): if self.Mode=="Manual": files=QFileDialog(self) files.setWindowTitle('Picket Fence 270') self.CurrentImages=files.getOpenFileNames(self,caption='Continuous Stripes (1)') ContStripesDlg1=ContStripesDlg.ContStripesWidget(self) #ContStripesDlg1.Img=DCMReader.ReadDCMFile(str(self.CurrentImages[0])) mypf = PicketFence(str(self.CurrentImages[0])) mypf.image.check_inversion() mypf.analyze(tolerance=0.5, action_tolerance=0.3,hdmlc=False) mypf.save_analyzed_image('PicketFence270',gaurd_rails=True,mlc_peaks=True,overlay=True,leaf_error_subplot=True) #print(mypf.num_pickets,'No. of pickets found') #print(mypf.return_results()) #mypf.plot_analyzed_image() AnalyzedImage=pl.imread('PicketFence270.png') ContStripesDlg1.Stripes.axes.imshow(AnalyzedImage) ContStripesDlg1.ResultsLabel.setText(mypf.return_results()) #mypf.plot_analyzed_image(ContStripesDlg1.Stripes) numPickets=str(mypf.num_pickets) ContStripesDlg1.Stripes.axes.set_title("No. of pickets found: "+numPickets+"Gantry=270") ContStripesDlg1.Stripes.axes.text(5,25,"Tol=0.5mm,Act_Tol=0.3mm",color='g') ContStripesDlg1.Stripes.axes.text(5,60,"Warning:Picket & leaf indexing starts with 0",color='r') self.SaveWidgetScreenShot(ContStripesDlg1,'PicketFence270.jpg') ContStripesDlg1.Stripes.axes.arrow(25,550, 50,0, head_width=10, head_length=25, fc='b', ec='b') ContStripesDlg1.Stripes.axes.arrow(25,550,0,-50, head_width=10, head_length=25, fc='b', ec='b') ContStripesDlg1.Stripes.axes.text(35,570,"Count",color='gray') ContStripesDlg1.Stripes.axes.text(5,515,"Count",color='gray',rotation=90) ContStripesDlg1.Stripes.axes.set_xlabel("Pixel No. G-T") ContStripesDlg1.Stripes.axes.set_ylabel("Pixel No. A-B") if self.Mode=="Manual": ContStripesDlg1.Stripes.draw() ContStripesDlg1.exec_() def AnalysePicketFence90(self): if self.Mode=="Manual": files=QFileDialog(self) files.setWindowTitle('Picket Fence 90') self.CurrentImages=files.getOpenFileNames(self,caption='Continuous Stripes (1)') ContStripesDlg1=ContStripesDlg.ContStripesWidget(self) #ContStripesDlg1.Img=DCMReader.ReadDCMFile(str(self.CurrentImages[0])) mypf = PicketFence(str(self.CurrentImages[0])) mypf.image.check_inversion() mypf.analyze(tolerance=0.5, action_tolerance=0.3,hdmlc=False) mypf.save_analyzed_image('PicketFence90',gaurd_rails=True,mlc_peaks=True,overlay=True,leaf_error_subplot=True) #print(mypf.num_pickets,'No. of pickets found') #print(mypf.return_results()) #mypf.plot_analyzed_image() AnalyzedImage=pl.imread('PicketFence90.png') ContStripesDlg1.Stripes.axes.imshow(AnalyzedImage) ContStripesDlg1.ResultsLabel.setText(mypf.return_results()) #mypf.plot_analyzed_image(ContStripesDlg1.Stripes) numPickets=str(mypf.num_pickets) ContStripesDlg1.Stripes.axes.set_title("No. of pickets found: "+numPickets+"Gantry=90") ContStripesDlg1.Stripes.axes.text(5,25,"Tol=0.5mm,Act_Tol=0.3mm",color='g') ContStripesDlg1.Stripes.axes.text(5,60,"Warning:Picket & leaf indexing starts with 0",color='r') self.SaveWidgetScreenShot(ContStripesDlg1,'PicketFence90.jpg') ContStripesDlg1.Stripes.axes.arrow(25,550, 50,0, head_width=10, head_length=25, fc='b', ec='b') ContStripesDlg1.Stripes.axes.arrow(25,550,0,-50, head_width=10, head_length=25, fc='b', ec='b') ContStripesDlg1.Stripes.axes.text(35,570,"Count",color='gray') ContStripesDlg1.Stripes.axes.text(5,515,"Count",color='gray',rotation=90) ContStripesDlg1.Stripes.axes.set_xlabel("Pixel No. G-T") ContStripesDlg1.Stripes.axes.set_ylabel("Pixel No. A-B") if self.Mode=="Manual": ContStripesDlg1.Stripes.draw() ContStripesDlg1.exec_() def AnalyseWedges(self,title): if self.Mode=="Manual": files=QFileDialog(self) files.setWindowTitle(title) if title=='XWedges': self.CurrentImages=files.getOpenFileNames(self,caption='X-Wedges') else: self.CurrentImages=files.getOpenFileNames(self,caption='Y-Wedges') WedgeDlg1=WedgeDlg.WedgeWidget(self) WedgeDlg1.setWindowTitle(title) yWedge1=DCMReader.ReadDCMFile(str(self.CurrentImages[0])) WedgeDlg1.Img1=yWedge1 WedgeDlg1.Wedge1.axes.imshow(WedgeDlg1.Img1,cmap='gray') if self.WedgeType=='X': WedgeDlg1.Wedge1.axes.set_title('Wedge1 -X') else: WedgeDlg1.Wedge1.axes.set_title('Wedge1 -Y') WedgeDlg1.Wedge1.axes.hold(True) EPIDType=np.shape(yWedge1) if EPIDType[0]==768: WedgeDlg1.Wedge1.axes.plot(self.Iso[0],self.Iso[1],'y+',markersize=20) else: WedgeDlg1.Wedge1.axes.plot(256,192,'y+',markersize=20) WedgeDlg1.Wedge1.axes.set_xlabel('Pixel No. A-B') WedgeDlg1.Wedge1.axes.set_ylabel('Pixel No. T-G') if self.Mode=="Manual": WedgeDlg1.Wedge1.draw() yWedge2=DCMReader.ReadDCMFile(str(self.CurrentImages[1])) WedgeDlg1.Img2=yWedge2 WedgeDlg1.Wedge2.axes.imshow(WedgeDlg1.Img2,cmap='gray') if self.WedgeType=='X': WedgeDlg1.Wedge2.axes.set_title('Wedge2 -x') else: WedgeDlg1.Wedge2.axes.set_title('Wedge2 -y') WedgeDlg1.Wedge2.axes.hold(True) if EPIDType[0]==768: WedgeDlg1.Wedge2.axes.plot(self.Iso[0],self.Iso[1],'y+',markersize=20) else: WedgeDlg1.Wedge2.axes.plot(256,192,'y+',markersize=20) WedgeDlg1.Wedge2.axes.set_xlabel('Pixel No. A-B') WedgeDlg1.Wedge2.axes.set_ylabel('Pixel No. T-G') if self.Mode=="Manual": WedgeDlg1.Wedge2.draw() combiWedges=yWedge1+yWedge2 WedgeDlg1.Img3=combiWedges WedgeDlg1.CombinedWedges.axes.imshow(WedgeDlg1.Img3,cmap='gray') if self.WedgeType=='X': WedgeDlg1.CombinedWedges.axes.set_title('Combined Wedges-X') else: WedgeDlg1.CombinedWedges.axes.set_title('Combined Wedges-Y') WedgeDlg1.CombinedWedges.axes.hold(True) if EPIDType[0]==768: WedgeDlg1.CombinedWedges.axes.plot(self.Iso[0],self.Iso[1],'y+',markersize=20) else: WedgeDlg1.CombinedWedges.axes.plot(256,192,'y+',markersize=20) # WedgeDlg1.CombinedWedges.axes.set_xlim(0,1024) # WedgeDlg1.CombinedWedges.axes.set_ylim(0,768) WedgeDlg1.CombinedWedges.axes.set_xlabel('Pixel No. A-B') WedgeDlg1.CombinedWedges.axes.set_ylabel('Pixel No. T-G') if self.Mode=="Manual": WedgeDlg1.CombinedWedges.draw() WedgeDlg1.plotProfiles(self.WedgeType) #print(self.WedgeType,"WedgeType") if self.Mode=="Manual": WedgeDlg1.exec_() if self.WedgeType=='X': self.SaveWidgetScreenShot(WedgeDlg1,'XWedges.jpg') if self.WedgeType=='Y': self.SaveWidgetScreenShot(WedgeDlg1,'YWedges.jpg') def AnalyseXWedges(self): self.WedgeType='X' self.AnalyseWedges('XWedges') def AnalyseYWedges(self): self.WedgeType='Y' self.AnalyseWedges('YWedges') def AnalyseComplexFields(self,ComplexType): files=QFileDialog(self) #Read images only if not in auto mode if self.Mode!="Auto": if ComplexType=='A': files.setWindowTitle('ComplexA') self.CurrentImages=files.getOpenFileNames(self,caption='ComplexA') else: files.setWindowTitle('ComplexB') self.CurrentImages=files.getOpenFileNames(self,caption='ComplexB') ComplexDlg1=ComplexDlg.ComplexABWidget(self) if ComplexType=='A': ComplexDlg1.setWindowTitle('ComplexA') else: ComplexDlg1.setWindowTitle('ComplexB') ComplexField=DCMReader.ReadDCMFile(self.CurrentImages[0]) EPIDType=(np.shape(ComplexField)) #print(EPIDType[0],EPIDType[1]) ComplexDlg1.Img1=ComplexField ComplexDlg1.mplwidget.axes.imshow(ComplexDlg1.Img1,cmap='gray') ComplexDlg1.mplwidget.axes.hold(True) ComplexDlg1.mplwidget.axes.plot(self.Iso[0],self.Iso[1],'y+',markersize=20) ComplexDlg1.mplwidget.axes.set_xlim(0,EPIDType[1]) ComplexDlg1.mplwidget.axes.set_ylim(0,EPIDType[0]) ComplexDlg1.mplwidget.axes.set_xlabel('Pixel No. A-B') ComplexDlg1.mplwidget.axes.set_ylabel('Pixel No. T-G') edge_sobel = sobel(ComplexDlg1.Img1) ComplexDlg1.mplwidget.axes.hold(True) ComplexDlg1.mplwidget.axes.imshow(edge_sobel,cmap='spring') ComplexDlg1.cmap.setCurrentIndex(4) #print(self.ComplexType,"ComplexType") if self.ComplexType=='A': ComplexDlg1.mplwidget.axes.set_title('ComplexA') self.SaveWidgetScreenShot(ComplexDlg1,'ComplexA.jpg') pl.imsave('ComplexA.jpg',ComplexDlg1.Img1) Img1=pl.imread('ComplexA.jpg') if EPIDType[0]==384: Img2=pl.imread('ComplexAOrgRefas500.jpg') else: Img2=pl.imread('ComplexAOrgRef.jpg') self.MSEComplexA=np.round(self.mse(Img1,Img2)) #print(self.MSEComplexA) elif self.ComplexType=='B': ComplexDlg1.mplwidget.axes.set_title('ComplexB') self.SaveWidgetScreenShot(ComplexDlg1,'ComplexB.jpg') pl.imsave('ComplexB.jpg',ComplexDlg1.Img1) Img1=pl.imread('ComplexB.jpg') if EPIDType[0]==384: Img2=pl.imread('ComplexBOrgRefas500.jpg') else: Img2=pl.imread('ComplexBOrgRef.jpg') self.MSEComplexB=np.round(self.mse(Img1,Img2)) #print(self.MSEComplexB) if self.Mode=="Manual": ComplexDlg1.mplwidget.draw() ComplexDlg1.exec_() def AnalyseComplexA(self): self.ComplexType='A' self.AnalyseComplexFields(self.ComplexType) def AnalyseComplexB(self): self.ComplexType='B' self.AnalyseComplexFields(self.ComplexType) def AnalysePyramids(self): if self.Mode=="Manual": files=QFileDialog(self) files.setWindowTitle('Pyramids') self.CurrentImages=files.getOpenFileNames(self,caption='Pyramids') PyramidDlg1=PyramidDlg.PyramidWidget(self) PyramidDlg1.Img1=DCMReader.ReadDCMFile(str(self.CurrentImages[0])) PyramidDlg1.Img2=DCMReader.ReadDCMFile(str(self.CurrentImages[1])) PyramidDlg1.cmap1.setCurrentIndex(3) PyramidDlg1.cmap2.setCurrentIndex(3) EPIDType=np.shape(PyramidDlg1.Img1) PyramidDlg1.pyramid1.axes.imshow(PyramidDlg1.Img1,cmap='cool') edge_sobel1 = sobel(PyramidDlg1.Img1) PyramidDlg1.pyramid1.axes.hold(True) PyramidDlg1.pyramid1.axes.imshow(edge_sobel1,cmap='cool',alpha=0.5) PyramidDlg1.pyramid1.axes.hold(True) PyramidDlg1.pyramid1.axes.plot(self.Iso[0],self.Iso[1],'y+',markersize=20) # if EPIDType==384: # PyramidDlg1.pyramid1.axes.set_xlim(170,330) # PyramidDlg1.pyramid1.axes.set_ylim(110,270) # else: # PyramidDlg1.pyramid1.axes.set_xlim(330,660) # PyramidDlg1.pyramid1.axes.set_ylim(240,540) PyramidDlg1.pyramid1.axes.set_xlabel('Pixel No. A-B') PyramidDlg1.pyramid1.axes.set_ylabel('Pixel No. T-G') PyramidDlg1.pyramid1.draw() PyramidDlg1.pyramid2.axes.imshow(PyramidDlg1.Img2,cmap='cool') edge_sobel2 = sobel(PyramidDlg1.Img2) PyramidDlg1.pyramid2.axes.hold(True) PyramidDlg1.pyramid2.axes.imshow(edge_sobel2,cmap='cool',alpha=0.5) PyramidDlg1.pyramid2.axes.hold(True) PyramidDlg1.pyramid2.axes.plot(self.Iso[0],self.Iso[1],'y+',markersize=20) # if EPIDType==384: # PyramidDlg1.pyramid2.axes.set_xlim(170,330) # PyramidDlg1.pyramid2.axes.set_ylim(110,270) # else: # PyramidDlg1.pyramid2.axes.set_xlim(330,660) # PyramidDlg1.pyramid2.axes.set_ylim(240,540) PyramidDlg1.pyramid2.axes.set_xlabel('Pixel No. A-B') PyramidDlg1.pyramid2.axes.set_ylabel('Pixel No. T-G') PyramidDlg1.pyramid2.draw() if self.Mode=="Manual": PyramidDlg1.exec_() self.SaveWidgetScreenShot(PyramidDlg1,'Pyramids.jpg') pl.imsave('Pyramid1.jpg',PyramidDlg1.Img1) Img1=pl.imread('Pyramid1.jpg') if EPIDType[0]==384: Img2=pl.imread('Pyramid1OrgRefas500.jpg') else: Img2=pl.imread('Pyramid1OrgRef.jpg') self.MSEPyramid1=np.round(self.mse(Img1,Img2)) pl.imsave('Pyramid2.jpg',PyramidDlg1.Img2) Img1=pl.imread('Pyramid2.jpg') if EPIDType[0]==384: Img2=pl.imread('Pyramid2OrgRefas500.jpg') else: Img2=pl.imread('Pyramid2OrgRef.jpg') self.MSEPyramid2=np.round(self.mse(Img1,Img2)) def AnalyseContStripes(self): files=QFileDialog(self) files.setWindowTitle('Picket Fence') self.CurrentImages=files.getOpenFileNames(self,caption='Picket Fence') ContStripesDlg1=ContStripesDlg.ContStripesWidget(self) ContStripesDlg1.Img=DCMReader.ReadDCMFile(str(self.CurrentImages[0])) mypf = PicketFence(str(self.CurrentImages[0])) mypf.image.check_inversion() mypf.analyze(tolerance=0.50, action_tolerance=0.3,hdmlc=False) mypf.save_analyzed_image('PicketFence',gaurd_rails=True,mlc_peaks=True,overlay=True) #print(mypf.num_pickets,'No. of pickets found') print("SID:",mypf.image.SID) AnalyzedImage=pl.imread('PicketFence.png') ContStripesDlg1.Stripes.axes.imshow(AnalyzedImage) ContStripesDlg1.ResultsLabel.setText(mypf.return_results()) #mypf.plot_analyzed_image(ContStripesDlg1.Stripes) ContStripesDlg1.Stripes.draw() ContStripesDlg1.exec_() self.SaveWidgetScreenShot(ContStripesDlg1,'PicketFence.jpg') def AnalyseSSS(self): if self.Mode=="Manual": files=QFileDialog(self) files.setWindowTitle('Synchronised Segment Stripes') self.CurrentImages=files.getOpenFileNames(self,caption='Synchronised Segment Stripes') SSSDlg1=SSSDlg.SSSWidget(self) SSSDlg1.Img1=DCMReader.ReadDCMFile(str(self.CurrentImages[0])) SSSDlg1.SSS1.axes.imshow(SSSDlg1.Img1,cmap='gray') SSSDlg1.Img2=DCMReader.ReadDCMFile(str(self.CurrentImages[1])) SSSDlg1.SSS2.axes.imshow(SSSDlg1.Img2,cmap='gray') SSSDlg1.Img3=DCMReader.ReadDCMFile(str(self.CurrentImages[2])) SSSDlg1.SSS3.axes.imshow(SSSDlg1.Img3,cmap='gray') SSSDlg1.Img4=DCMReader.ReadDCMFile(str(self.CurrentImages[3])) SSSDlg1.SSS4.axes.imshow(SSSDlg1.Img4,cmap='gray') SSSDlg1.ImgCombi=SSSDlg1.Img1+SSSDlg1.Img2+SSSDlg1.Img3+SSSDlg1.Img4 SSSDlg1.SSSCombi.axes.imshow(SSSDlg1.ImgCombi,cmap='gray') EPIDType=np.shape(SSSDlg1.Img1) pl.imsave('SSS.jpg',SSSDlg1.ImgCombi) Img1=pl.imread('SSS.jpg') if EPIDType[0]==384: Img2=pl.imread('SSSOrgRefas500.jpg') else: Img2=pl.imread('SSSOrgRef.jpg') self.MSESSS=np.round(self.mse(Img1,Img2)) if self.Mode=="Manual": SSSDlg1.exec_() def AnalyseNSS(self): if self.Mode=="Manual": files=QFileDialog(self) files.setWindowTitle('Non-Synchronised Segment Stripes') self.CurrentImages=files.getOpenFileNames(self,caption='Non-Synchronised Segment Stripes') SSSDlg1=SSSDlg.SSSWidget(self) SSSDlg1.Img1=DCMReader.ReadDCMFile(str(self.CurrentImages[0])) SSSDlg1.SSS1.axes.imshow(SSSDlg1.Img1,cmap='gray') SSSDlg1.Img2=DCMReader.ReadDCMFile(str(self.CurrentImages[1])) SSSDlg1.SSS2.axes.imshow(SSSDlg1.Img2,cmap='gray') SSSDlg1.Img3=DCMReader.ReadDCMFile(str(self.CurrentImages[2])) SSSDlg1.SSS3.axes.imshow(SSSDlg1.Img3,cmap='gray') SSSDlg1.Img4=DCMReader.ReadDCMFile(str(self.CurrentImages[3])) SSSDlg1.SSS4.axes.imshow(SSSDlg1.Img4,cmap='gray') SSSDlg1.ImgCombi=SSSDlg1.Img1+SSSDlg1.Img2+SSSDlg1.Img3+SSSDlg1.Img4 SSSDlg1.SSSCombi.axes.imshow(SSSDlg1.ImgCombi,cmap='gray') EPIDType=np.shape(SSSDlg1.Img1) pl.imsave('NSS.jpg',SSSDlg1.ImgCombi) Img1=pl.imread('NSS.jpg') if EPIDType[0]==384: Img2=pl.imread('NSSOrgRefas500.jpg') else: Img2=pl.imread('NSSOrgRef.jpg') self.MSENSS=np.round(self.mse(Img1,Img2)) if self.Mode=="Manual": SSSDlg1.exec_() def AnalyseMLCAlign(self): files=QFileDialog(self) files.setWindowTitle('MLC Alignment') if self.Mode=="Manual": self.CurrentImages=files.getOpenFileNames(self,caption='MLC ALignment (2)') MLCAlignDlg1=MLCAlignDlg.MLCAlignWidget(self) MLC1=DCMReader.ReadDCMFile(str(self.CurrentImages[0])) MLCAlignDlg1.Img1=MLC1 MLC2=DCMReader.ReadDCMFile(str(self.CurrentImages[1])) MLCAlignDlg1.Img2=MLC2 MLCAlignDlg1.Img3=MLCAlignDlg1.Img1+MLCAlignDlg1.Img2 EPIDType=(np.shape(MLC1)) MLCAlignDlg1.MLCAlignWidget.axes.imshow(MLCAlignDlg1.Img3,cmap='cool') MLCAlignDlg1.MLCAlignWidget.axes.set_title('MLC Alignment') MLCAlignDlg1.MLCAlignWidget.axes.hold(True) #1mm x-guard lines xLine1=np.linspace(0,EPIDType[1],50) if EPIDType[0]==384: spacing=0.784 else: spacing=0.397 xLine2=np.ones(50)*(EPIDType[0]/2.0)-(0.5/spacing)#0.5 mm away from centreline MLCAlignDlg1.MLCAlignWidget.axes.plot(xLine1,xLine2,color='y',linewidth=1) xLine3=np.linspace(0,EPIDType[1],50) xLine4=np.ones(50)*(EPIDType[0]/2.0)+(0.5/spacing)#0.5 mm away from centreline MLCAlignDlg1.MLCAlignWidget.axes.plot(xLine3,xLine4,color='y',linewidth=1) #1mm y-guard lines yLine1=np.linspace(0,EPIDType[0],50) yLine2=np.ones(50)*(EPIDType[1]/2.0)-(0.5/spacing)#0.5 mm away from centreline MLCAlignDlg1.MLCAlignWidget.axes.plot(yLine2,yLine1,color='y',linewidth=1) yLine3=np.linspace(0,EPIDType[0],50) yLine4=np.ones(50)*(EPIDType[1]/2.0)+(0.5/spacing)#0.5 mm away from centreline MLCAlignDlg1.MLCAlignWidget.axes.plot(yLine4,yLine3,color='y',linewidth=1) #MLCAlignDlg1.MLCAlignWidget.axes.plot(self.Iso[0],self.Iso[1],'y+',markersize=20) MLCAlignDlg1.MLCAlignWidget.axes.set_xlim(0,EPIDType[1]) MLCAlignDlg1.MLCAlignWidget.axes.set_ylim(0,EPIDType[0]) MLCAlignDlg1.MLCAlignWidget.axes.set_xlabel('Pixel No. A-B') MLCAlignDlg1.MLCAlignWidget.axes.set_ylabel('Pixel No. T-G') MLCAlignDlg1.MLCAlignWidget.draw() self.SaveWidgetScreenShot(MLCAlignDlg1,'MLCAlignment.jpg') if self.Mode=="Manual": MLCAlignDlg1.exec_() def SaveWidgetScreenShot(self,Widget,filename): pixelMap=QPixmap(Widget.size()) Widget.render(pixelMap, QPoint(), QRegion(Widget.size())) pixelMap.save(filename,quality=100) def mse(self,imageA, imageB): # the 'Mean Squared Error' between the two images is the # sum of the squared difference between the two images; # NOTE: the two images must have the same dimension err = np.sum((imageA.astype("float") - imageB.astype("float")) ** 2) err /= float(imageA.shape[0] * imageA.shape[1]) # return the MSE, the lower the error, the more "similar" # the two images are return err def AnalyseCT(self): ct_folder = r"C:\MLC QA\Imgs\MLCQA28AUG2015\QA_Tube_Replc_11092015" myct = CBCT(ct_folder) myct.analyze() myct.return_results() myct.plot_analyzed_image() def CreatePDFReport(self): mcID=QInputDialog.getText(self, "Enter M/C ID", "M/C ID:", 0) msrBy=QInputDialog.getText(self, "Initials", "Measured by:", 0) if mcID[1]==True and msrBy[1]==True: #Setting up header & preparing page today=date.today() day=str(today.day) month=str(today.month) year=str(today.year) dateStr=day+'_'+month+'_'+year self.reportStr="MLCQA"+"_"+dateStr+'.pdf' c = canvas.Canvas(self.reportStr,pagesize=A4) c.drawImage('Logo.png',350,775,8*cm,1.75*cm) text1="MLC QA Report:"+dateStr c.drawString(100,800,text1) mcIDStr="MC ID:"+mcID[0] c.drawString(100,750,mcIDStr) #ComplexA c.line(50,700,580,700) mseStr="Mean Square Error:"+str(self.MSEComplexA) c.drawString(270,675,"Complex-A") c.drawString(250,650,mseStr) c.drawImage('ComplexA.jpg',100,150,15*cm,18*cm,preserveAspectRatio=True) text2='Measured by: '+str(msrBy[0]) text3='Checked by:_______________' c.drawString(100,80,text2) c.drawString(100,50,text3) c.line(50,125,580,125) #ComplexB c.showPage()#Move to next page c.line(50,700,580,700) mseStr="Mean Square Error:"+str(self.MSEComplexB) c.drawString(270,675,"Complex-B") c.drawString(250,650,mseStr) c.drawImage('ComplexB.jpg',100,150,15*cm,18*cm,preserveAspectRatio=True) text2='Measured by: '+str(msrBy[0]) text3='Checked by:_______________' c.drawString(100,80,text2) c.drawString(100,50,text3) c.line(50,125,580,125) #MLC Bank Alignment c.showPage()#Move to next page c.line(50,700,580,700) c.drawString(250,675,"MLC Bank Alignment") c.drawImage('MLCAlignment.jpg',100,150,15*cm,18*cm,preserveAspectRatio=True) text2='Measured by: '+str(msrBy[0]) text3='Checked by:_______________' c.drawString(100,80,text2) c.drawString(100,50,text3) c.line(50,125,580,125) #NSS c.showPage()#Move to next page c.line(50,700,580,700) c.drawString(240,675,"Non-synchronised Segment Stripes") c.drawImage('NSS.jpg',100,150,15*cm,18*cm,preserveAspectRatio=True) mseStr="Mean Square Error:"+str(self.MSENSS) c.drawString(270,650,mseStr) text2='Measured by: '+str(msrBy[0]) text3='Checked by:_______________' c.drawString(100,80,text2) c.drawString(100,50,text3) c.line(50,125,580,125) #Picket fence#Gantry=0 c.showPage()#Move to next page c.line(50,700,580,700) c.drawString(250,675,"Picket Fence Gantry=0") c.drawImage('PicketFence0.jpg',100,150,13*cm,18*cm,preserveAspectRatio=True) text2='Measured by: '+str(msrBy[0]) text3='Checked by:_______________' c.drawString(100,80,text2) c.drawString(100,50,text3) c.line(50,125,580,125) #Picket fence#Gantry=270 c.showPage()#Move to next page c.line(50,700,580,700) c.drawString(250,675,"Picket Fence Gantry=270") c.drawImage('PicketFence270.jpg',100,150,13*cm,18*cm,preserveAspectRatio=True) text2='Measured by: '+str(msrBy[0]) text3='Checked by:_______________' c.drawString(100,80,text2) c.drawString(100,50,text3) c.line(50,125,580,125) #Picket fence#Gantry=90 c.showPage()#Move to next page c.line(50,700,580,700) c.drawString(250,675,"Picket Fence Gantry=90") c.drawImage('PicketFence90.jpg',100,150,13*cm,18*cm,preserveAspectRatio=True) text2='Measured by: '+str(msrBy[0]) text3='Checked by:_______________' c.drawString(100,80,text2) c.drawString(100,50,text3) c.line(50,125,580,125) #Pyramid1 c.showPage()#Move to next page c.line(50,700,580,700) c.drawString(270,675,"Pyramid1") c.drawImage('Pyramid1.jpg',100,150,15*cm,18*cm,preserveAspectRatio=True) mseStr="Mean Square Error:"+str(self.MSEPyramid1) c.drawString(260,650,mseStr) text2='Measured by: '+str(msrBy[0]) text3='Checked by:_______________' c.drawString(100,80,text2) c.drawString(100,50,text3) c.line(50,125,580,125) #Pyramid2 c.showPage()#Move to next page c.line(50,700,580,700) c.drawString(270,675,"Pyramid2") c.drawImage('Pyramid2.jpg',100,150,15*cm,18*cm,preserveAspectRatio=True) mseStr="Mean Square Error:"+str(self.MSEPyramid2) c.drawString(260,650,mseStr) text2='Measured by: '+str(msrBy[0]) text3='Checked by:_______________' c.drawString(100,80,text2) c.drawString(100,50,text3) c.line(50,125,580,125) #SSS c.showPage()#Move to next page c.line(50,700,580,700) c.drawString(240,675,"Synchronised Segment Stripes") c.drawImage('NSS.jpg',100,150,15*cm,18*cm,preserveAspectRatio=True) mseStr="Mean Square Error:"+str(self.MSESSS) c.drawString(270,650,mseStr) text2='Measured by: '+str(msrBy[0]) text3='Checked by:_______________' c.drawString(100,80,text2) c.drawString(100,50,text3) c.line(50,125,580,125) #X-Wedges c.showPage()#Move to next page c.line(50,700,580,700) c.drawString(270,675,"XWedges") c.drawImage('XWedges.jpg',100,150,15*cm,18*cm,preserveAspectRatio=True) text2='Measured by: '+str(msrBy[0]) text3='Checked by:_______________' c.drawString(100,80,text2) c.drawString(100,50,text3) c.line(50,125,580,125) #Y-Wedges c.showPage()#Move to next page c.line(50,700,580,700) c.drawString(270,675,"YWedges") c.drawImage('YWedges.jpg',100,150,15*cm,18*cm,preserveAspectRatio=True) text2='Measured by: '+str(msrBy[0]) text3='Checked by:_______________' c.drawString(100,80,text2) c.drawString(100,50,text3) c.line(50,125,580,125) #Save the PDF to working dir c.save() def AutoReport(self): self.Mode="Auto" dirPath= str(QFileDialog.getExistingDirectory(self, "Select Directory")) files=os.listdir(dirPath) for x in range (0,np.size(files),1): files[x]=dirPath+'\\'+files[x] if (np.size(files)!=21): errorMsg=QErrorMessage(self) errorMsg.setWindowTitle("Error") errorMsg.showMessage("No. of files must be 21","Error") errorMsg.exec_() else: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) #ComplexA self.CurrentImages.append(files[0]) self.ComplexType='A' self.AnalyseComplexFields('A') self.CurrentImages.clear() #ComplexB self.CurrentImages.append(files[1]) self.ComplexType='B' self.AnalyseComplexFields('B') self.CurrentImages.clear() #MLC Alignment self.CurrentImages.append(files[2]) self.CurrentImages.append(files[3]) self.AnalyseMLCAlign() self.CurrentImages.clear() #NSS self.CurrentImages.append(files[4]) self.CurrentImages.append(files[5]) self.CurrentImages.append(files[6]) self.CurrentImages.append(files[7]) self.AnalyseNSS() self.CurrentImages.clear() #Picket Fence- Gantry =0 self.CurrentImages.append(files[8]) self.AnalysePicketFence0() self.CurrentImages.clear() #Picket Fence- Gantry =270 self.CurrentImages.append(files[9]) self.AnalysePicketFence270() self.CurrentImages.clear() #Picket Fence- Gantry =90 self.CurrentImages.append(files[10]) self.AnalysePicketFence90() self.CurrentImages.clear() #Pyramids self.CurrentImages.append(files[11]) self.CurrentImages.append(files[12]) self.AnalysePyramids() self.CurrentImages.clear() #SSS self.CurrentImages.append(files[13]) self.CurrentImages.append(files[14]) self.CurrentImages.append(files[15]) self.CurrentImages.append(files[16]) self.AnalyseSSS() self.CurrentImages.clear() #X-Wedges self.WedgeType='X' self.CurrentImages.append(files[17]) self.CurrentImages.append(files[18]) self.AnalyseWedges("X") self.CurrentImages.clear() #Y-Wedges self.WedgeType='Y' self.CurrentImages.append(files[19]) self.CurrentImages.append(files[20]) self.AnalyseWedges("Y") self.CurrentImages.clear() #Restore normal cursor QApplication.restoreOverrideCursor() #Create a PDF report self.CreatePDFReport() #Revert back to manual mode self.Mode="Manual" os.startfile(self.reportStr)
class MainForm(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() # self.ui.setupUi(self) # super(Window, self).__init__(parent) self.ui.setupUi(self) self.connect(self.ui.addParticipantButton, QtCore.SIGNAL('pressed()'),self.newParticipant) self.connect(self.ui.removeParticipantButton, QtCore.SIGNAL('pressed()'),self.removeParticipant) self.connect(self.ui.listOfParticipants, QtCore.SIGNAL("itemChanged(QListWidgetItem*)"),self.changeParticipantName) # self.connect(self.ui.listOfParticipants, QtCore.SIGNAL("itemClicked(QListWidgetItem*)"),self.addParticipantToGroup) self.connect(self.ui.addGroupButton, QtCore.SIGNAL('pressed()'),self.newGroup) self.connect(self.ui.removeGroupButton, QtCore.SIGNAL('pressed()'),self.removeGroup) self.connect(self.ui.addToGroupButton, QtCore.SIGNAL('pressed()'),self.addParticipantToGroup) self.connect(self.ui.removeFromGroupButton, QtCore.SIGNAL('pressed()'),self.removeParticipantFromGroup) self.connect(self.ui.optimizeButton, QtCore.SIGNAL('pressed()'),self.optimizeGroups) self.connect(self.ui.chooseFileButton, QtCore.SIGNAL('pressed()'),self.openFile) def newParticipant(self): # name = random.randrange(0,10) i = 0 while self.ui.listOfParticipants.findItems("participant"+str(i), QtCore.Qt.MatchExactly).__len__() != 0: i = i+1 name = "participant"+str(i) participant = lab2.Participant(name) participantItem = QtGui.QListWidgetItem(name) participantItem.setData(32, participant) participantItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable) self.ui.listOfParticipants.addItem(participantItem) def removeParticipant(self): participantItem = self.ui.listOfParticipants.selectedItems()[0] participant = participantItem.data(32).toPyObject() for groupItem in self.ui.listOfGroups.findItems(":"+participant.name, QtCore.Qt.MatchContains): groupName = groupItem.text().replace(":"+participant.name, "") groupItem.setText(groupName) group = groupItem.data(32).toPyObject() group.removeParticipant(participant) self.ui.listOfParticipants.takeItem(self.ui.listOfParticipants.row(participantItem)) def changeParticipantName(self): participantItem = self.ui.listOfParticipants.selectedItems()[0] participant = participantItem.data(32).toPyObject() participantOldName = participant.name participant.name = participantItem.text() participantItem.setData(32, participant) for groupItem in self.ui.listOfGroups.findItems(":"+participantOldName, QtCore.Qt.MatchContains): groupName = groupItem.text().replace(":"+participantOldName, ":"+participantItem.text()) groupItem.setText(groupName) def newGroup(self): group = lab2.Group([]) group.participants = [] i = 0 while self.ui.listOfGroups.findItems("group"+str(i), QtCore.Qt.MatchStartsWith).__len__() != 0: i = i+1 name = "group"+str(i) groupItem = QtGui.QListWidgetItem(name) groupItem.setData(32, group) groupItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.ui.listOfGroups.addItem(groupItem) def removeGroup(self): groupItem = self.ui.listOfGroups.selectedItems()[0] self.ui.listOfGroups.takeItem(self.ui.listOfGroups.row(groupItem)) def addParticipantToGroup(self): participantItem = self.ui.listOfParticipants.selectedItems()[0] groupItem = self.ui.listOfGroups.selectedItems()[0] participant = participantItem.data(32).toPyObject() group = groupItem.data(32).toPyObject() if not group.addParticipant(participant) == 0: groupName = groupItem.text() + ":" + participant.name groupItem.setText(groupName) def removeParticipantFromGroup(self): participantItem = self.ui.listOfParticipants.selectedItems()[0] groupItem = self.ui.listOfGroups.selectedItems()[0] participant = participantItem.data(32).toPyObject() group = groupItem.data(32).toPyObject() if not group.removeParticipant(participant) == 0: groupName = groupItem.text().replace(":"+participant.name, "") groupItem.setText(groupName) def optimizeGroups(self): groupList = lab2.Grouping() for groupItem in self.ui.listOfGroups.findItems("group", QtCore.Qt.MatchStartsWith): group = groupItem.data(32).toPyObject() groupList.addGroup(group) groupList.optimize() for groupItem in self.ui.listOfGroups.findItems("group", QtCore.Qt.MatchStartsWith): group = groupItem.data(32).toPyObject() if not group in groupList.group_list: self.ui.listOfGroups.takeItem(self.ui.listOfGroups.row(groupItem)) def openFile(self): filename = QtGui.QFileDialog.getOpenFileNames(self, 'Open File')
class GroundSystem(QtGui.QMainWindow): # # Init the class # def __init__(self, parent=None): QtGui.QMainWindow.__init__(self) # Init lists self.ipAddressesList = ['All'] self.spacecraftNames = ['All'] # Init GUI and set callback methods for buttons self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pushButtonStartTlm.clicked.connect(self.startTlmSystem) self.ui.pushButtonStartCmd.clicked.connect(self.startCmdSystem) def closeEvent(self, evnt): if self.RoutingService: self.RoutingService.stop() print("Stopped routing service") super(GroundSystem, self).closeEvent(evnt) # Read the selected spacecraft from combo box on GUI def getSelectedSpacecraftAddress(self): return str(self.ui.comboBoxIpAddresses.currentText()) # Returns the name of the selected spacecraft def getSelectedSpacecraftName(self): return self.spacecraftNames[self.ipAddressesList.index( self.getSelectedSpacecraftAddress())] # # Display popup with error # def DisplayErrorMessage(self, message): print(message) alert = QtGui.QMessageBox() alert.setText(message) alert.setIcon(QtGui.QMessageBox.Warning) alert.exec_() # Start the telemetry system for the selected spacecraft def startTlmSystem(self): selectedSpacecraft = self.getSelectedSpacecraftName() # Setup the subscription (to let know the telemetry system the messages it will be receiving) if selectedSpacecraft == 'All': subscription = '--sub=GroundSystem' else: subscription = '--sub=GroundSystem.' + selectedSpacecraft + '.TelemetryPackets' # Open Telemetry System system_call = '( cd Subsystems/tlmGUI/ && python3 TelemetrySystem.py ' + subscription + ' ) & ' os.system(system_call) # Start command system def startCmdSystem(self): os.system('( cd Subsystems/cmdGui/ && python3 CommandSystem.py ) & ') # Start FDL-FUL gui system #def startFDLSystem(self): # selectedSpacecraft = self.getSelectedSpacecraftName() # if selectedSpacecraft == 'All': # subscription = '' # self.DisplayErrorMessage('Cannot open FDL manager.\nNo spacecraft selected.') # else: # subscription = '--sub=GroundSystem.' + selectedSpacecraft # os.system('( cd Subsystems/fdlGui/ && python FdlSystem.py ' + subscription + ' ) & ') # Update the combo box list in gui def updateIpList(self, ip, name): self.ipAddressesList.append(ip) self.spacecraftNames.append(name) self.ui.comboBoxIpAddresses.addItem(ip) # Start the routing service (see RoutingService.py) def initRoutingService(self): self.RoutingService = RoutingService(self) self.connect(self.RoutingService, self.RoutingService.signalUpdateIpList, self.updateIpList) self.RoutingService.start()
class MainWindow(QtGui.QMainWindow): # Configuracion basica, de SEÑALES y de SLOTS de la GUI (ventana principal) def __init__(self, parent=None): super(MainWindow, self).__init__(parent) QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.actionSalir.triggered.connect(self.close) self.ui.actionConfiguracion.triggered.connect(self.Configuracion) self.ui.actionAcerca_de.triggered.connect(self.Acerca) self.ui.generar.clicked.connect(self.Generar) self.ui.pausar.clicked.connect(self.Pausar) self.ui.borrar.clicked.connect(self.Borrar) self.ui.borrar.clicked.connect(self.ui.senoidal.click) self.ui.offset.valueChanged.connect(self.Off) self.ui.frecuencia.valueChanged.connect(self.Frec) self.ui.senoidal.clicked.connect(self.Senoidal) self.ui.triangular.clicked.connect(self.Triangular) self.ui.rampa.clicked.connect(self.Rampa) self.ui.cuadrada.clicked.connect(self.Cuadrada) def Generar(self): # Funcion del boton "Generar" global Control Control = "1" try: Config = self.Configurar() signal = dev.write(1, Config, 0, 100) if signal: print("Se generó la señal") print("Se enviaron: " + str(signal) + " bytes: '" + str(Config) + "'") print("") else: print("Se produjo un error en el envio, revise la configuración") except: print("No se pudo configurar el dispositivo") def Pausar(self): # Funcion del boton "Pausar" global Control global Config if Control == "1" and Control != "0": Control = "0" Config = self.Configurar() signal = dev.write(1, Config, 0, 100) print("Se pausó la señal") print("Se enviaron: " + str(signal) + " bytes: '" + str(Config) + "'") print("") else: print("La señal ya se encuentra pausada") def Borrar(self): # Funcion del boton "Borrar" global Tipo global Frecuencia global Offset global Control global Config Tipo = "0" # Seno (tipo por defecto) Frecuencia = "5000" # 5000 Hz (frecuencia por defecto) Offset = "0" # 0V de offset (offset por defecto) Control = "0" # Desactivo la generación de la señal self.ui.frecuencia.setValue(5000) self.ui.offset.setValue(0) Config = self.Configurar() try: signal = dev.write(1, Config, 0, 100) if signal: print("Se configuró la señal por defecto") print("Se enviaron: " + str(signal) + " bytes: '" + str(Config) + "'") print("") else: print("Se produjo un error en el envio, revise la configuración") except: print("No se pudo configurar el dispositivo") def Senoidal(self): # Funcion del radio boton "Senoidal" global Tipo Tipo = "0" print("La señal es de tipo senoidal") def Triangular(self): # Funcion del radio boton "Triangular" global Tipo Tipo = "1" print("La señal es de tipo triangular") def Rampa(self): # Funcion del radio boton "Rampa" global Tipo Tipo = "2" print("La señal es de tipo rampa") def Cuadrada(self): # Funcion del radio boton "Cuadrada" global Tipo Tipo = "3" print("La señal es de tipo cuadrada") def Frec(self, Frec): # Funcion del spinbox de "Frecuencia" global Frecuencia Frecuencia = str(Frec) print("Frecuencia: " + Frecuencia) def Off(self, Off): # Funcion del slider de "Offset" global Offset self.ui.offset.setToolTip(_fromUtf8(str(-self.ui.offset.value()))) self.ui.lOffset.setText(_fromUtf8(str(-self.ui.offset.value()) + " %")) Offset = str(-Off) print("Offset: " + Offset) def Configurar(self): # Funcion que genera el vector de configuracion de la señal a enviar por USB global Tipo global Frecuencia global Offset global Control """ ORDEN DE LOS BYTES A ENVIAR: 1er BYTE --> TIPO DE SEÑAL [0 SENOIDAL, 1 TRIANGULAR, 2 RAMPA, 3 CUADRADA] --> N° en ASCII 2do BYTE --> FRECUENCIA [4] --------------> N° en ASCII 3er BYTE --> FRECUENCIA [3] --------------> N° en ASCII 4to BYTE --> FRECUENCIA [2] --------------> N° en ASCII 5to BYTE --> FRECUENCIA [1] --------------> N° en ASCII 6to BYTE --> FRECUENCIA [0] --------------> N° en ASCII 7mo BYTE --> OFFSET [SIGNO] --------------> Signo (+ o -) en ASCII 8vo BYTE --> OFFSET [2] ------------------> N° en ASCII 9no BYTE --> OFFSET [1] ------------------> N° en ASCII 10mo BYTE --> OFFSET [0] -----------------> N° en ASCII 11vo BYTE --> CONTROL [0 PARA, 1 INICIA] -> N° en ASCII """ if len(str(Frecuencia)) < 5 and len(str(Frecuencia)) > 3: Frecuencia = "0" + Frecuencia elif len(str(Frecuencia)) < 4 and len(str(Frecuencia)) > 2: Frecuencia = "00" + Frecuencia elif len(str(Frecuencia)) < 3 and len(str(Frecuencia)) > 1: Frecuencia = "000" + Frecuencia elif len(str(Frecuencia)) < 2: Frecuencia = "0000" + Frecuencia if int(Offset) >= 0: if len(Offset) == 3: Offset = "+" + Offset elif len(Offset) < 3 and len(Offset) > 1: Offset = "+0" + Offset elif len(Offset) < 2: Offset = "+00" + Offset elif int(Offset) < 0: if len(Offset) < 4 and len(Offset) > 2: Offset = "-0" + str(-int(Offset)) elif len(Offset) < 3: Offset = "-00" + str(-int(Offset)) Config = Tipo + str(Frecuencia) + str(Offset) + Control print(Config) return Config def Configuracion(self): # Funcion de llamada a la ventana de "Configuracion" self.w = ConfWindow() # self.w.show() self.w.exec_() # Una vez abierta solo se puede interactuar con esta ventana def Acerca(self): # Funcion de llamada a la ventana de informacion "Acerca de..." self.w = AcercaWindow() # self.w.show() self.w.exec_() # Una vez abierta solo se puede interactuar con esta ventana
class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.layout = QtGui.QGridLayout() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.load_data_tipo() self.signals() self.show() def signals(self): """Se conectan los botones y la señales de la interfaz""" self.ui.tabla_tipo.clicked.connect(self.tabla_tipo_clicked) self.ui.tabla_animal.clicked.connect(self.tabla_animal_clicked) self.ui.btn_editar_tipo.clicked.connect(self.editar_tipo_clicked) self.ui.btn_agregar_animal.clicked.connect(self.agregar_animal_clicked) self.ui.btn_editar_animal.clicked.connect(self.editar_animal_clicked) self.ui.eliminar_animal.clicked.connect(self.eliminar_animal_clicked) ###Esta funcion debería ser llamada desde el controlador### def load_data_tipo(self): """Funcion que carga todos los tipos de animales dentro de una grilla, a través del controlador se recibe la información con la cual posteriormente se llena la información de la grilla """ tipo = controller.carga_tipos() self.model = QtGui.QStandardItemModel(5, 1) self.model.setHorizontalHeaderItem(0, QtGui.QStandardItem(u"Tipo")) r = 0 for row in tipo: nombre = row.__dict__["nombre"] index = self.model.index(r, 0, QtCore.QModelIndex()) self.model.setData(index, nombre) r = r + 1 self.ui.tabla_tipo.horizontalHeader().setResizeMode( 0, self.ui.tabla_tipo.horizontalHeader().Stretch) self.ui.tabla_tipo.setModel(self.model) self.ui.tabla_tipo.setColumnWidth(0, 187) def tabla_tipo_clicked(self): """Borra todo lo del widget donde se muestran las imágenes, se limpian los labels donde se despliega información del animal , y luego se despliega la info del tipo de animal""" self.borralayout(self.layout) index = self.ui.tabla_tipo.currentIndex() id_tipo = index.row() + 1 tipo = controller.carga_info_tipo(id_tipo) self.ui.label_datos.setText("") self.ui.label_nombre_cientifico.setText("") self.ui.label_descripcion_tipo.setText(tipo.descripcion) self.load_data_animal(id_tipo) ###Esta funcion también debería ser llamada desde el controlador ### def load_data_animal(self, id_tipo): """Funcion que carga todos los animales de un tipo en la grilla""" animales = controller.carga_animales(id_tipo) self.model = QtGui.QStandardItemModel(animales.__len__(), 1) self.model.setHorizontalHeaderItem(0, QtGui.QStandardItem(u"Animal")) r = 0 for row in animales: nombre = row.__dict__["nombre_comun"] index = self.model.index(r, 0, QtCore.QModelIndex()) self.model.setData(index, nombre) r = r + 1 self.ui.lbl_cant_ani.setText(str(r)) self.ui.tabla_animal.horizontalHeader().setResizeMode( 0, self.ui.tabla_animal.horizontalHeader().Stretch) self.ui.tabla_animal.setModel(self.model) self.ui.tabla_animal.setColumnWidth(0, 241) def tabla_animal_clicked(self): """Cuando se presiona la tabla animal, se presiona un animal, el a través del nombre del animal, se llama el controlador, el cual retorna el Animal() y se cargan en los respectivos labels los datos correspondientes, los cuales son sacados de los atributos del respectivo objeto""" index = self.ui.tabla_animal.currentIndex() nombre = index.data() # nombre del animal animal = controller.carga_animal(nombre) self.ui.label_nombre_cientifico.setText(animal.nombre_cientifico) self.ui.label_datos.setText(animal.datos) self.despliega_imagenes(animal.id_animal) def editar_tipo_clicked(self): """Al presionar el boton editar se llama al formulario para poder hacer esta acción, para esto primero se verifica que se haya presionado un animal de la grilla""" index_ed = self.ui.tabla_tipo.currentIndex() if index_ed.row() == -1: # No se ha seleccionado una fila self.errorMessageDialog = QtGui.QErrorMessage(self) self.errorMessageDialog.showMessage("Debe seleccionar un tipo") return False else: id_tipo = index_ed.row() + 1 self.edit = EditarTipo(id_tipo=id_tipo, callback=self.load_data_tipo) def agregar_animal_clicked(self): """Llama al formulario el cual permite agregar un animal""" self.formulario = Formulario(callback=self.tabla_tipo_clicked) def editar_animal_clicked(self): """Llama al mismo formulario que el anterior, pero se pasan diferentes parámetros, la que este permite editar la información del animal.-""" index = self.ui.tabla_animal.currentIndex() if index.row() == -1: # No se ha seleccionado una fila self.errorMessageDialog = QtGui.QErrorMessage(self) self.errorMessageDialog.showMessage("Debe seleccionar un animal") return False else: animal = index.data() self.formulario = Formulario(editar=1, nom_animal=animal, callback=self.tabla_tipo_clicked) def eliminar_animal_clicked(self): """Se verifica que se haya seleccionado un animal de la grilla, luego se pregunta si de verdad se desea eliminar este animal, luego se llama al controlador el cual elimina el animal de la base de datos.-""" model = self.ui.tabla_animal.model() index = self.ui.tabla_animal.currentIndex() if index.row() == -1: # No se ha seleccionado una fila self.errorMessageDialog = QtGui.QErrorMessage(self) self.errorMessageDialog.showMessage("Debe seleccionar un animal") return False else: mensaje = u"¿Desea eliminar el animal seleccionado?" self.pregunta = QtGui.QMessageBox.question(self, self.tr("Eliminar"), mensaje , QtGui.QMessageBox.StandardButton.Yes | QtGui.QMessageBox.StandardButton.No) if self.pregunta == QtGui.QMessageBox.Yes: animal = model.index( index.row(), 0, QtCore.QModelIndex()).data() controller.elimina_animal(animal) self.tabla_tipo_clicked() def despliega_imagenes(self, id_animal): """Se reciben todas las una lista de objetos del tipo Imagen, se crea una grid layout, donde se despliegan las imágenes, por cada imagen se agrega un boton el cual es conectado a las funciones crea_funcion_eliminar y crea_funcion_editar, que crear una funcion por cada boton creado con lo cual luego se puede editar o eliminar las imagenes, se carga una imagen vacia con el botón agregar, donde el usuario posteriormente puede agregar la imagen que el desee""" self.borralayout(self.layout) imagenes = controller.obtener_imagenes(id_animal) cant_imagenes = len(imagenes) labels = {} widget = {} layoutsV = {} layoutsH = {} btns_el = {} btns_ed = {} filas = math.ceil(cant_imagenes / 3.0) k = 0 cont = 0 for i in range(int(filas)): for j in range(3): cont = cont + 1 if(k <= cant_imagenes - 1): ubicacion = (imagenes[k].__dict__["ubicacion"].decode( 'utf-8')) id_imagen = (imagenes[k].__dict__["id_imagen"]) widget[(i, j)] = QtGui.QWidget() layoutsV[(i, j)] = QtGui.QVBoxLayout() layoutsH[(i, j)] = QtGui.QHBoxLayout() btns_el[(i, j)] = QtGui.QPushButton("Eliminar") self.funcion_boton_eliminar = self.crea_funcion_eliminar( id_imagen, ubicacion, id_animal) btns_el[(i, j)].clicked.connect( self.funcion_boton_eliminar) btns_ed[(i, j)] = QtGui.QPushButton("Editar") self.funcion_boton_editar = self.crea_funcion_editar( id_imagen, ubicacion) btns_ed[(i, j)].clicked.connect( self.funcion_boton_editar) labels[(i, j)] = QtGui.QLabel(ubicacion) self.myPixmap = QtGui.QPixmap(ubicacion) self.myScaledPixmap = self.myPixmap.scaled(200, 200, QtCore.Qt.KeepAspectRatio) labels[(i, j)].setPixmap(self.myScaledPixmap) layoutsV[(i, j)].addWidget(labels[(i, j)]) layoutsH[(i, j)].addWidget(btns_ed[(i, j)]) layoutsH[(i, j)].addWidget(btns_el[(i, j)]) layoutsV[(i, j)].addLayout(layoutsH[(i, j)]) widget[(i, j)].setLayout(layoutsV[(i, j)]) self.layout.addWidget(widget[(i, j)], i, j) k = k + 1 if(cont == cant_imagenes + 1): btn_agregar = QtGui.QPushButton("Agregar") btn_agregar.clicked.connect(self.boton_agregar_imagen) layoutsV[(i, j)] = QtGui.QVBoxLayout() widget[(i, j)] = QtGui.QWidget() labels[(i, j)] = QtGui.QLabel() self.myPixmap = QtGui.QPixmap("imagenes/sin_imagen.jpg") self.myScaledPixmap = self.myPixmap.scaled(200, 200, QtCore.Qt.KeepAspectRatio) labels[(i, j)].setPixmap(self.myScaledPixmap) layoutsV[(i, j)].addWidget(labels[(i, j)]) layoutsV[(i, j)].addWidget(btn_agregar) widget[(i, j)].setLayout(layoutsV[(i, j)]) self.layout.addWidget(widget[(i, j)], i, j) if (cant_imagenes / 3 == filas): btn_agregar = QtGui.QPushButton("Agregar") btn_agregar.clicked.connect(self.boton_agregar_imagen) layoutsV[(filas + 1, 1)] = QtGui.QVBoxLayout() widget[(filas + 1, 1)] = QtGui.QWidget() labels[(filas + 1, 1)] = QtGui.QLabel() self.myPixmap = QtGui.QPixmap("imagenes/sin_imagen.jpg") self.myScaledPixmap = self.myPixmap.scaled(200, 200, QtCore.Qt.KeepAspectRatio) labels[(filas + 1, 1)].setPixmap(self.myScaledPixmap) layoutsV[(filas + 1, 1)].addWidget(labels[(filas + 1, 1)]) layoutsV[(filas + 1, 1)].addWidget(btn_agregar) widget[(filas + 1, 1)].setLayout(layoutsV[(filas + 1, 1)]) self.layout.addWidget(widget[(filas + 1, 1)], filas + 1, 1) self.ui.scrollAreaWidgetContents.setLayout(self.layout) self.ui.scrollAreaWidgetContents.show() def borralayout(self, aLayout): """Elimina todo el layout y elementos del widget donde se almacenan las imágenes y los botones de cada imágen""" while aLayout.count(): item = aLayout.takeAt(0) item.widget().deleteLater() def crea_funcion_eliminar(self, id_imagen, ubicacion, id_animal): """Crea una funcion para cada imagen que se agrega al widget donde se despliegan la imagen, esta función permite eliminar la fotografía""" def funcion_boton(): mensaje = u"¿Desea eliminar la imagen seleccionada?" self.pregunta = QtGui.QMessageBox.question(self, self.tr("Eliminar"), mensaje , QtGui.QMessageBox.StandardButton.Yes | QtGui.QMessageBox.StandardButton.No) if self.pregunta == QtGui.QMessageBox.Yes: controller.elimina_foto(id_imagen, ubicacion) self.despliega_imagenes(id_animal) return funcion_boton def crea_funcion_editar(self, id_imagen, ubicacion): """Crea una funcion para cada imagen que se agrega al widget donde se despliegan la imagen, esta función permite editar la fotografía""" def funcion_boton(): fileName = QtGui.QFileDialog.getOpenFileName(self, "Elige la imagen", os.getcwd()) directorio = fileName[0] num = random.randrange(1, 20) num_str = str(num) nombre_foto = "{0}_{1}".format( num_str, QtCore.QFileInfo(directorio).fileName()) ubicacion_nueva_foto = "imagenes/{0}".format(nombre_foto) shutil.copy2(directorio, ubicacion_nueva_foto) controller.actualiza_foto(id_imagen, ubicacion_nueva_foto, callback=self.tabla_animal_clicked) return funcion_boton def boton_agregar_imagen(self): """Permite al usuario elegir la fotografia desde su computador, se verifica que se haya presionado algún animal, se abre la fotografía, se obtienen la diferente información necesaria de esta, y luego se llama al controlador con el cual agrega la fotografia al animal correspondiente en la base de datos, además en esta funcion se copia la fotografía a la carpeta /imagenes """ index = self.ui.tabla_animal.currentIndex() if index.row() == -1: # No se ha seleccionado una fila self.errorMessageDialog = QtGui.QErrorMessage(self) self.errorMessageDialog.showMessage("Debe seleccionar un animal") return False else: fileName = QtGui.QFileDialog.getOpenFileName(self, "Elige la imagen", os.getcwd(), "*.jpg *.jpeg *.png *.gif") directorio = fileName[0] num = random.randrange(1, 20) num_str = str(num) nombre_foto = "{0}_{1}".format( num_str, QtCore.QFileInfo(directorio).fileName()) shutil.copy2(directorio, "imagenes/{0}".format(nombre_foto)) index = self.ui.tabla_animal.currentIndex() animal = controller.carga_animal(index.data()) controller.agregar_foto(animal.id_animal, nombre_foto, callback=self.tabla_animal_clicked)
class MyApplication(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self)
class Start(QtGui.QWidget): #the class for the main window def __init__(self ,parent = None): super(Start, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.measurement_Windows = [] self.masterFilename = 'config&data\master_config.txt' self.fileDict = {} self.open_master_config() #signals and slots self.ui.button_measurement.clicked.connect(self.measurement) self.ui.button_GAS.clicked.connect(self.open_GAS) self.ui.button_INST.clicked.connect(self.open_INST) self.ui.button_presets.clicked.connect(self.open_Preset) self.ui.button_analysis.clicked.connect(self.open_analysis) def any_running(self): #checks if there are an windows running. Returns a boolean. return any(window.isRunning for window in self.measurement_Windows) def allow_run(self): #checks all the measurement windows and returns true if none are running. Returns False if one is. Ensures that communications to instruments dont' cross paths #also checks if any of them have the same datafile dataFiles = {} #count the apperaences of each dataFilename for window in self.measurement_Windows: if window.dataFilename not in dataFiles: dataFiles[window.dataFilename] = 0 dataFiles[window.dataFilename]+=1 dataFilesInvalid = any(value>1 for value in dataFiles.itervalues()) measurementRunning = self.any_running() message = '' if dataFilesInvalid: message = 'There was a conflict with the data files' elif measurementRunning: message = 'There seems to be a measurement running already.' return not dataFilesInvalid and not measurementRunning, message #if the dataFiles are invalid or a measurement is running, we don't want to allow a meausrement def check_runs(self, callerWindow): for window in self.measurement_Windows: if window is not callerWindow: window.check_run() def closeEvent(self, event): #make sure that all the windows close when the main one does. if self.measurement_Windows: response = QtGui.QMessageBox.warning(self, 'Warning!', 'Closing this window will close all the measurements too.\nAre you sure you want to close?', buttons=QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, defaultButton=QtGui.QMessageBox.No) if response == QtGui.QMessageBox.No: event.ignore() return for window in self.measurement_Windows: window.close() event.accept() def measurement(self): presetsFile = open(self.fileDict['PRESET'] , 'r') presetNames = ['None'] with open(self.fileDict['PRESET'], 'r') as presetFile: for line in presetFile: #gather all the names from the preset file values = parseKeyValue(line) if values is not None and values[0] == 'Name': presetNames.append(values[1]) import preset_dialog_main self.presetDialog = preset_dialog_main.PresetDialog(presetNames) if not self.presetDialog.exec_(): return else: presetName = self.presetDialog.getChoice() if presetName == 'None': presetName = None from pyvisa import visa_exceptions import GASconfig try: GASdict, INSTdict = GASconfig.getsAndSetsFromConfig(self.fileDict['GAS']) except visa_exceptions.VisaIOError: QtGui.QMessageBox.warning(self, 'Warning', 'There was a problem opening the connections to the instruments. Check that they are configured.', buttons=QtGui.QMessageBox.Ok, defaultButton=QtGui.QMessageBox.Ok) return import MeasurementGUI_main self.measurement_Windows.append(MeasurementGUI_main.Start(self.fileDict, presetName,GASdict, INSTdict, parent = self)) self.measurement_Windows[-1].showMaximized() def open_analysis(self): #hans't been implemented; instead opens a dialog warning the user QtGui.QMessageBox.warning(self, 'Analysis', 'The Analysis feature has not been implemented yet. Sorry!', buttons=QtGui.QMessageBox.Ok, defaultButton=QtGui.QMessageBox.Ok) def open_GAS(self): #opens the GAS config module import Gasconfig_GUI_main self.gasConfig = Gasconfig_GUI_main.Start(self.fileDict['GAS'], self) self.gasConfig.show() def open_INST(self): #opens the INSt config module import INSTconfig_GUI_main self.INSTconfg = INSTconfig_GUI_main.Start(self.fileDict['INST'], self) self.INSTconfg.show() def open_Preset(self): #opens the delete preset dialog. import deletePreset_main self.presetConfig = deletePreset_main.deletePreset(self.fileDict['PRESET']) self.presetConfig.show() def open_master_config(self): #opens the measurement config and creates the self.fileDict dictionary, listing the files where the configs are stored on this machine import os compName = os.environ['COMPUTERNAME'] lines = [] master_config = open(self.masterFilename, 'r') for line in master_config: lines.append(line) master_config.close() for index in xrange(len(lines)): tup = parseKeyValue(lines[index]) if tup is not None and tup[1] == compName: #found our computer for i in xrange(index + 1, index + 4): tup = parseKeyValue(lines[i]) if tup is not None: self.fileDict[tup[0]] = tup[1] #add the file type and name into the dicitonary. break def remove_window(self, child): #deletes the window rom the list. This frees up memory for index,window in enumerate(self.measurement_Windows): if child is window: window.close() break self.measurement_Windows.pop(index) #let the garbage collector delete it def update_GAS_INST(self): #updates the GAS and INST objects for each child window. from pyvisa import visa_exceptions import GASconfig try: GASdict, INSTdict = GASconfig.getsAndSetsFromConfig(self.fileDict['GAS']) except visa_exceptions.VisaIOError: QtGui.QMessageBox.warning(self, 'Warning', 'There was a problem opening the connections to the instruments. Check that they are configured.', buttons=QtGui.QMessageBox.Ok, defaultButton=QtGui.QMessageBox.Ok) return for window in self.measurement_Windows: #send this update down to the lower windows while window.isRunning: pass #wait until the window is done running. window.GASdict = GASdict window.INSTdict = INSTdict window.open_GASFile()
class PyFinModelsApp(QtGui.QMainWindow) : def __init__(self) : QtGui.QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.chartrow = 0 self.chartcol = 0 self.ui.frmNotify.hide() self.sheetrow = 0 self.propertyChanged = functools_partial(PyFinModelsApp.propertyChangeEvent, self) self.connect(self.ui.tblSheet, QtCore.SIGNAL('itemChanged(QTableWidgetItem *)'), self.propertyChangeEvent) def propertyChangeEvent(self, item): if isinstance(item, QPropertyVal): self.modelProperties.setPropVal(item.associatedProperty(), item.text()) def getSheet(self) : return self.ui.tblSheet def getCodeEditor(self) : return self.ui.txtCode def getModelHintsTextbox(self) : return self.ui.txtModelHints def addProperties(self, mprops) : col = 0 self.modelProperties = mprops props = mprops.getProps() for key in props : itemKey = QtGui.QTableWidgetItem(key) itemKey.setBackground(QtGui.QBrush(QtGui.QColor('Gray'))) fnt = itemKey.font() itemKey.setToolTip(mprops.getPropHelp(key)) fnt.setWeight(QtGui.QFont.Bold) itemKey.setFont(fnt) itemKey.setFlags(QtCore.Qt.ItemIsEnabled) self.getSheet().setItem(self.sheetrow, col, itemKey) itemVal = QPropertyVal(str(mprops.getPropVal(key))) itemVal.setAssociatedProperty(key) itemVal.setBackground(QtGui.QBrush(QtGui.QColor("Red"))) itemVal.setToolTip(mprops.getPropHelp(key)) self.getSheet().setItem(self.sheetrow, col + 1, itemVal) self.sheetrow += 1 def addModelActions(self, actionDict) : col = 0 for x in actionDict : btn = QtGui.QPushButton(x, self.getSheet()) btn.setFont(self.getSheet().font()) ahandler = functools_partial(PyFinModelsApp.actionHandler, self, actionDict[x]) self.connect(btn, QtCore.SIGNAL('clicked(bool)'), ahandler) self.getSheet().setCellWidget(self.sheetrow, col, btn) col += 1 def actionHandler(self, actionTarget): actionTarget(self.modelProperties) pass def add1DData(self, name, data) : self.sheetrow += 1 col = 0 for x in data : item = QtGui.QTableWidgetItem(x) item.setBackground(QtGui.QBrush(QtGui.QColor("Brown"))) item.setFlags(QtCore.Qt.ItemIsEnabled) self.getSheet().setItem(self.sheetrow, col, item) col += 1 def showOutputHeading(self, name) : self.sheetrow += 1 itemKey = QtGui.QTableWidgetItem(name) itemKey.setBackground(QtGui.QBrush(QtGui.QColor("Pink"))) fnt = itemKey.font() fnt.setWeight(QtGui.QFont.Bold) itemKey.setFont(fnt) itemKey.setFlags(QtCore.Qt.ItemIsEnabled) self.getSheet().setItem(self.sheetrow, 0, itemKey) def add2DData(self, name, data) : self.showOutputHeading(name) col = 0 for x in data : self.sheetrow += 1 col = 0 for y in x : item = QtGui.QTableWidgetItem(str(y)) item.setBackground(QtGui.QBrush(QtGui.QColor(255, 100, 100))) item.setFlags(QtCore.Qt.ItemIsEnabled) self.getSheet().setItem(self.sheetrow, col, item) col += 1 def add2DChart(self, name, pyFinChart) : self.ui.chartGrid.addWidget(pyFinChart, self.chartrow, self.chartcol) if self.chartcol == 3 : self.chartrow += 1 self.chartcol = 0 else : self.chartcol += 1 def loadModel(self, model) : self.getSheet().clearContents() self.addProperties(model.getProperties()) self.addModelActions(model.getModelActions())
class StartQT4(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self)