Beispiel #1
0
class MainWindow(QtGui.QFrame) :

	def __init__(self) :
		super(MainWindow, self).__init__()
		MainWindowInstance.Instance = self
		
		# Membres
		self.m_ui = Ui_MainWindow()
		self.m_ui.setupUi(self)
		
		# Connexions
		self.m_ui.buttonBooking.clicked.connect(self.bookingClicked)
		self.m_ui.buttonClients.clicked.connect(self.clientsClicked)
		self.m_ui.buttonBills.clicked.connect(self.billsClicked)
		
		# Etat initial
		self.bookingClicked()
		# self.clientsClicked()
		# self.billsClicked()
		
	def bookingClicked(self) :
		self.m_ui.content.setCurrentWidget(self.m_ui.bookingList)
	
	def clientsClicked(self) :
		self.m_ui.content.setCurrentWidget(self.m_ui.clientList)
	
	def billsClicked(self) :
		self.m_ui.content.setCurrentWidget(self.m_ui.billList)
Beispiel #2
0
class MainWindow(QMainWindow):
    startBut = Signal()

    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.manager = Manager(self)
        self.__threadRun = QThread()
        self.__threadRun.start()
        self.manager.moveToThread(self.__threadRun)

        self.ui.openFile_button.clicked.connect(self.openFileButtonClicked)
        self.ui.start_button.clicked.connect(self.startButtonClicked)
        self.startBut.connect(self.manager.startButtonClicked)

        self.manager.sendMessageConsole.connect(self.setMessage)

    def setMessage(self, message):
        self.ui.console_textBrowser.append(message)

    def openFileButtonClicked(self):
        path_to_file, _ = QFileDialog.getOpenFileName(
            self, self.tr("Load Image"), self.tr("~/Desktop/"),
            self.tr("Images (*.png *.jpg)"))
        self.manager.setImage(path_to_file)
        pix = QPixmap(path_to_file)
        pix = pix.scaled(640, 480, Qt.KeepAspectRatio)
        self.ui.inputImage_label.setPixmap(pix)

    def startButtonClicked(self):
        self.startBut.emit()
Beispiel #3
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.dicomVisWidget = DicomVis()
        self.ui.verticalLayout.insertWidget(0, self.dicomVisWidget)

        studypath = "C:\\DICOM_resources\\BRAINIX\\T1-3D-FFE-C - 801"
        self.dicomVisWidget.load_study_from_path(studypath)

    @QtCore.pyqtSlot()
    def on_loadStudyBtn_clicked(self):
        dicompath = str(QtGui.QFileDialog.getExistingDirectory(None, "Open Directory", "/home", QtGui.QFileDialog.ShowDirsOnly))
        try:
            self.dicomVisWidget.load_study_from_path(dicompath)
        except:
            infobox = QtGui.QMessageBox(QtGui.QMessageBox.Critical, "Error", "Ups! Something went wrong")
            infobox.exec_()


    @QtCore.pyqtSlot()
    def on_actionAbout_triggered(self):
        infobox = QtGui.QMessageBox(QtGui.QMessageBox.Information, "About", "by: MKozuch")
        infobox.exec_()
Beispiel #4
0
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.dicomVisWidget = DicomVis()
        self.opened_list = []

        self.ui.verticalLayout.insertWidget(0, self.dicomVisWidget)

        #studypath = ''
        #self.dicomVisWidget.load_study_from_path(studypath)

    def closeEvent(self, event):
        replay = QtWidgets.QMessageBox.question(
            self, 'Message', "Are you sure to quit?",
            QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
            QtWidgets.QMessageBox.No)
        if replay == QtWidgets.QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def center(self):
        qr = self.frameGeometry()
        #得到主窗口大小
        cp = QtWidgets.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    @QtCore.pyqtSlot()
    def on_loadStudyBtn_clicked(self):
        #dicompath = str(QtWidgets.QFileDialog.getExistingDirectory(None, "Open Directory", "/home", QtWidgets.QFileDialog.ShowDirsOnly))

        self.dicomVisWidget.load_study_from_path('./17/17_clean2.nrrd')
        '''
        except:
            infobox = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Critical, "Error", "Something went wrong")
            infobox.exec_()
        '''
        '''
        self.opened_list.append(dicompath.split('/')[-1])
        self.model = QtGui.QStandardItemModel()
        for file in self.opened_list:
            item = QtGui.QStandardItem(file)
            item.setCheckState(False)
            item.setCheckable(True)
            self.model.appendRow(item)
            self.dicomVisWidget.ui.opened_view.setModel(self.model)
        '''

    @QtCore.pyqtSlot()
    def on_actionAbout_triggered(self):
        infobox = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Information,
                                        "About", "by:")
        infobox.exec_()
Beispiel #5
0
class ApplicationWindow(QtGui.QMainWindow):
    def __init__(self, sources, sourceTree, sourceKeeper):
        print('in ApplicationWindow.__init__(self)')
        QtGui.QMainWindow.__init__(self)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.sourceKeeper = sourceKeeper
        #         self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        #         self.setWindowTitle('Visibilty plotter.')

        #         self.fileMenu = QtGui.QMenu('&File', self)
        #         self.fileMenu.addAction('&Quit', self.fileQuit, QtCore.Qt.CTRL+QtCore.Qt.Key_Q)
        #         self.menuBar().addMenu(self.fileMenu)

        #         self.main_widget = QtGui.QWidget(self)
        self.l = QtGui.QVBoxLayout(self.ui.visPlotCanvas)
        self.vp = VisibilityPlotCanvas(self,
                                       width=5,
                                       height=4,
                                       sources=sources,
                                       sourceKeeper=sourceKeeper,
                                       dpi=100)

        self.l.addWidget(self.vp)
        self.ui.sourceSelector.setModel(sourceTree)
        self.sourceKeeper.sourceSelector = self.ui.sourceSelector
        QtCore.QObject.connect(
            self.ui.sourceSelector.selectionModel(),
            QtCore.SIGNAL('selectionChanged(QItemSelection, QItemSelection)'),
            self.sourceKeeper.sourceSelected)
        QtCore.QObject.connect(self.ui.actionFlip_activity,
                               QtCore.SIGNAL(_fromUtf8("activated()")),
                               self.sourceKeeper.swapSelected)

#         table_header = ['Project', 'Source name', 'grade', 'frontend']
#         table_header = [ 'Source name']
#         self.ui.sourceListTable.verticalHeader().hide()
#         self.ui.sourceListTable.setColumnCount(len(table_header))
#         self.ui.sourceListTable.setHorizontalHeaderLabels(table_header)
#         self.ui.sourceListTable.setRowCount(len(sources.objs))
#         for i, obj in enumerate(sources.objs):
#             self.ui.sourceListTable.setItem(i, 0, QtGui.QTableWidgetItem(obj.name))
#             self.ui.sourceListTable.setItem(i, 1, QTableWidgetItem(obj.name))
#             self.ui.sourceListTable.setItem(i, 2, QTableWidgetItem(obj.name))
#             self.ui.sourceListTable.setItem(i, 3, QTableWidgetItem(obj.name))

#         self.visPlotCanvas.setLayout(self.l)
#         self.visPlotCanvas = self.main_widget

#         self.statusBar().showMessage('APEX-1')

    def update(self):
        self.vp.update_figure()
Beispiel #6
0
class ApplicationWindow(QtGui.QMainWindow):
    def __init__(self, sources, sourceTree, sourceKeeper):
        print('in ApplicationWindow.__init__(self)')
        QtGui.QMainWindow.__init__(self)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.sourceKeeper = sourceKeeper
#         self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
#         self.setWindowTitle('Visibilty plotter.')

#         self.fileMenu = QtGui.QMenu('&File', self)
#         self.fileMenu.addAction('&Quit', self.fileQuit, QtCore.Qt.CTRL+QtCore.Qt.Key_Q)
#         self.menuBar().addMenu(self.fileMenu)

#         self.main_widget = QtGui.QWidget(self)
        self.l = QtGui.QVBoxLayout(self.ui.visPlotCanvas)
        self.vp = VisibilityPlotCanvas(self, width=5, height=4, 
                sources=sources, sourceKeeper=sourceKeeper, dpi=100)


        self.l.addWidget(self.vp)
        self.ui.sourceSelector.setModel(sourceTree)
        self.sourceKeeper.sourceSelector = self.ui.sourceSelector
        QtCore.QObject.connect(self.ui.sourceSelector.selectionModel(),
                QtCore.SIGNAL('selectionChanged(QItemSelection, QItemSelection)'), 
                self.sourceKeeper.sourceSelected)
        QtCore.QObject.connect(self.ui.actionFlip_activity, 
                QtCore.SIGNAL(_fromUtf8("activated()")),
                self.sourceKeeper.swapSelected)

#         table_header = ['Project', 'Source name', 'grade', 'frontend']
#         table_header = [ 'Source name']
#         self.ui.sourceListTable.verticalHeader().hide()
#         self.ui.sourceListTable.setColumnCount(len(table_header))
#         self.ui.sourceListTable.setHorizontalHeaderLabels(table_header)
#         self.ui.sourceListTable.setRowCount(len(sources.objs))
#         for i, obj in enumerate(sources.objs):
#             self.ui.sourceListTable.setItem(i, 0, QtGui.QTableWidgetItem(obj.name))
#             self.ui.sourceListTable.setItem(i, 1, QTableWidgetItem(obj.name))
#             self.ui.sourceListTable.setItem(i, 2, QTableWidgetItem(obj.name))
#             self.ui.sourceListTable.setItem(i, 3, QTableWidgetItem(obj.name))

#         self.visPlotCanvas.setLayout(self.l)
#         self.visPlotCanvas = self.main_widget

#         self.statusBar().showMessage('APEX-1')

    def update(self):
        self.vp.update_figure()
Beispiel #7
0
class MainWindow(QtGui.QMainWindow):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        desktopSize = QDesktopWidget().screenGeometry()
        top=(desktopSize.height()/2)-(450/2)
        left=(desktopSize.width()/2)-(300/2)
        self.move(left, top)
        self.connect(self.ui.friendsListWidget, QtCore.SIGNAL('itemDoubleClicked (QListWidgetItem *)'), self.openConversation)
        self.talks = dict()
        self.messages = collections.defaultdict(list)

    def openConversation(self):
        jid = None
        try:
            jid = self.ui.friendsListWidget.selectedItems()[0].text()
        except IndexError:
            pass

        if jid:
            talk = ConversationWindow(parent=self)

            try:
                y = self.talks[jid]
            except KeyError:
                y = False
            finally:
                if not y:
                    talk.setup(jid, self.talks, self.messages)
                    talk.show()
                    self.talks[jid] = True

    def getMessages(self):
        messages, pressences = xmpp.Xmpp().current()
        for jid in messages:
            split = jid.split('/')
            self.messages[split[0]].append(jid+": "+messages[jid][0])
        self.refreshTimer = threading.Timer(0.5, client_app.getMessages)
        self.refreshTimer.start()

    def closeEvent(self, event):
        self.refreshTimer.cancel()
        event.accept()
Beispiel #8
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.dicomVisWidget = iDicom()
        self.ui.verticalLayout.insertWidget(0, self.dicomVisWidget)

        dir_path = os.path.dirname(os.path.realpath(__file__))
        studyPath = str(os.path.join(dir_path, 'images'))
        self.dicomVisWidget.load_study_from_path(studyPath)

    @QtCore.pyqtSlot()
    def on_loadStudyBtn_clicked(self):
        dicompath = str(
            QtGui.QFileDialog.getExistingDirectory(
                None, "Open Directory", "/home",
                QtGui.QFileDialog.ShowDirsOnly))
        try:
            self.dicomVisWidget.load_study_from_path(dicompath)
        except:
            infobox = QtGui.QMessageBox(QtGui.QMessageBox.Critical, "Error",
                                        "Something went wrong =/")
            infobox.exec_()

    @QtCore.pyqtSlot()
    def on_actionAbout_triggered(self):
        infobox = QtGui.QMessageBox(QtGui.QMessageBox.Information, "About",
                                    "iDicom 2017")
        infobox.exec_()

    @QtCore.pyqtSlot()
    def on_actionOpen_triggered(self):
        dicompath = str(
            QtGui.QFileDialog.getExistingDirectory(
                None, 'Open Directory', '/home',
                QtGui.QFileDialog.ShowDirsOnly))
        try:
            self.dicomVisWidget.load_study_from_path(dicompath)
        except:
            infobox = QtGui.QMessageBox(QtGui.QMessageBox.Critical, 'Error',
                                        'Something went wrong =/')
            infobox.exec_()
class MyMainWindow(Ui_MainWindow):

    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__()
        # QtGui.QMainWindow.__init__(self,parent)
        self.ui = Ui_MainWindow(self)
        self.ui.setupUi(self)
        self.setupConnect()

    def setupConnect(self):
        self.ui.pushButton.clicked.connect(self.answer)
        self.ui.pushButton_bind.clicked.connect(self.bind)

    def answer(self):
        self.s.sendto('answer'.encode(), self.desc)

    def bind(self):
        self.desc = ('<broadcast>', 12345)
        self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        bindstr = 'name' + self.ui.lineEdit_Name.text()
        self.s.sendto(bindstr.encode(), self.desc)
Beispiel #10
0
class MyMainWindow(Ui_MainWindow):

    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__()
        # QtGui.QMainWindow.__init__(self,parent)
        self.ui = Ui_MainWindow(self)
        self.ui.setupUi(self)
        self.setupConnect()

        self.isOpenCom = False

        self.serverURL = 'http://166.111.53.137:8080/makerPlus/servlet/'
#         self.serverURL = 'http://59.66.81.161:8080/makerPlus/servlet/'
#         self.serverURL = 'http://172.27.35.42:8080/makerPlus/servlet/'
#         self.busyBar = BusyBar("Connecting to Server...")
#         self.busyBar.setLabelText("Connecting")
#         self.busyBar.show()
        try:
            self.eventList = requests.get(self.serverURL + 'Event').json()
            self.updateEventList(self.eventList)
            self.eventSelected()
#             self.busyBar.close()
        except:
#             self.busyBar.close()
            QtGui.QMessageBox.warning(self, "Error", "Can't connect to server",
                                              QtGui.QMessageBox.Cancel, QtGui.QMessageBox.NoButton,
                                              QtGui.QMessageBox.NoButton)

        strFileType = "TXT File (*.txt)"
        self.localFilePath = QtGui.QFileDialog.getSaveFileName(self,
                "Save MSpectrum",
                "/home",
                strFileType)

    def __del__(self):
        print("in del")
        try:
            self.mySerialThread.stop()
        except:
            pass

    def setupConnect(self):
        self.ui.pushButton.clicked.connect(self.upLoad)
#         self.ui.comboBox.currentIndexChanged.connect(self.eventSelected)
        self.ui.comboBox.activated.connect(self.eventSelected)
        self.ui.pushButton_openCom.clicked.connect(self.onPressCom)

    def upLoad(self):
        uploadParameters = dict()
        for i in range(len(self.currentEventParameters)):
            if i == 0:
                uploadParameters[self.currentEventParameters[i]] = self.ui.lineEdit_1.text()
            elif i == 1:
                uploadParameters[self.currentEventParameters[i]] = self.ui.lineEdit_2.text()
            elif i == 2:
                uploadParameters[self.currentEventParameters[i]] = self.ui.lineEdit_3.text()
            elif i == 3:
                uploadParameters[self.currentEventParameters[i]] = self.ui.lineEdit_4.text()
            elif i == 4:
                uploadParameters[self.currentEventParameters[i]] = self.ui.lineEdit_5.text()
            elif i == 5:
                uploadParameters[self.currentEventParameters[i]] = self.ui.lineEdit_6.text()
            elif i == 6:
                uploadParameters[self.currentEventParameters[i]] = self.ui.lineEdit_7.text()
            elif i == 7:
                uploadParameters[self.currentEventParameters[i]] = self.ui.lineEdit_8.text()

        r = requests.post(self.serverURL + "Event?EventName=" + self.currentEventName, data={'data': str(uploadParameters)})
#         r = requests.post(self.serverURL + "Event?EventName=" + self.currentEventName, data={'data': u"{'some':'毕滢'}"})
        print(r.text)
        if r.status_code != 200:
            QtGui.QMessageBox.warning(self, "Error",
                                              "Upload Error: " + str(r.status_code),
                                              QtGui.QMessageBox.Cancel, QtGui.QMessageBox.NoButton,
                                              QtGui.QMessageBox.NoButton)
        else:
            isShowDialog = False
            if self.currentEventName == "RegisterEvent":
                dialogShowStr = r.text
                isShowDialog = True
            elif self.currentEventName == "CheckEvent":
                memberInfo = r.json()
                phoneNum = memberInfo["电话"]
                showPhoneNum = "手机尾号:" + phoneNum[len(phoneNum) - 4:len(phoneNum)]
                self.ui.label_return_info_1.setText(memberInfo["姓名"])
                self.ui.label_return_info_2.setText(showPhoneNum)
                isShowDialog = False
            elif self.currentEventName == "LotteryEvent":
                memberInfo = r.json()
                phoneNum = memberInfo["电话"]
                showPhoneNum = "手机尾号:" + phoneNum[len(phoneNum) - 4:len(phoneNum)]
                self.ui.label_return_info_1.setText(memberInfo["姓名"])
                self.ui.label_return_info_2.setText(showPhoneNum)
                dialogShowStr = "获得15点经验值!!"
                isShowDialog = True

            if isShowDialog:
                QtGui.QMessageBox.warning(self, "Done!",
                                                  dialogShowStr,
                                                  QtGui.QMessageBox.Information, QtGui.QMessageBox.NoButton,
                                                  QtGui.QMessageBox.NoButton)

            self.f = open(self.localFilePath, 'a')
            self.f.write(str(uploadParameters))
            self.f.write(" ")
            self.f.write(r.text)
#             self.f.write("\n")
            self.f.close()

            # copy id to clipboard
            clipboard = QtGui.QApplication.clipboard()
            mimeData = QtCore.QMimeData()
#             mimeData.setText(r.text)
            mimeData.setText(r.text[0:len(r.text) - 2])
            clipboard.setMimeData(mimeData)

    def updateEventList(self, eventList):
        self.ui.comboBox.clear()
        for i in range(len(eventList)):
            self.ui.comboBox.addItem(eventList[i])

    def eventSelected(self):
        self.currentEventName = self.eventList[self.ui.comboBox.currentIndex()]
        self.currentEventParameters = requests.get(self.serverURL + 'Event?EventName=' + self.currentEventName).json()
#         self.currentEventParameters = requests.get(self.serverURL + 'Tester').json()

        # clean label text
        self.ui.label_1.setText("")
        self.ui.label_2.setText("")
        self.ui.label_3.setText("")
        self.ui.label_4.setText("")
        self.ui.label_5.setText("")
        self.ui.label_6.setText("")
        self.ui.label_7.setText("")
        self.ui.label_8.setText("")

        for i in range(len(self.currentEventParameters)):
            if i == 0:
                self.ui.label_1.setText(self.currentEventParameters[i])
            elif i == 1:
                self.ui.label_2.setText(self.currentEventParameters[i])
            elif i == 2:
                self.ui.label_3.setText(self.currentEventParameters[i])
            elif i == 3:
                self.ui.label_4.setText(self.currentEventParameters[i])
            elif i == 4:
                self.ui.label_5.setText(self.currentEventParameters[i])
            elif i == 5:
                self.ui.label_6.setText(self.currentEventParameters[i])
            elif i == 6:
                self.ui.label_7.setText(self.currentEventParameters[i])
            elif i == 7:
                self.ui.label_8.setText(self.currentEventParameters[i])

    def onPressCom(self):
        if not self.isOpenCom:
            try:
                self.mySerialThread = SerialThread(int(self.ui.lineEdit_com.text()) - 1)
                self.mySerialThread.myCommunicator.trigger.connect(self.updateIDfromSerial)
                self.mySerialThread.start()
                self.isOpenCom = True
                self.ui.pushButton_openCom.setText("关闭串口")
            except:
                self.mySerialThread.stop()
                QtGui.QMessageBox.warning(self, "Error",
                                                  "Can't open Com",
                                                  QtGui.QMessageBox.Cancel, QtGui.QMessageBox.NoButton,
                                                  QtGui.QMessageBox.NoButton)
        else:
            self.mySerialThread.stop()
            self.isOpenCom = False
            self.ui.pushButton_openCom.setText("开启串口")

    def updateIDfromSerial(self):
        self.id = self.mySerialThread.id
        if not self.currentEventName == "RegisterEvent":
            idStr = str(self.id)
            self.ui.lineEdit_1.setText(idStr[2:len(idStr) - 5])
        print(self.id)
class Win(QtGui.QMainWindow):
    keith = None
    SR830 = None
    resSig = QtCore.pyqtSignal(object)
    phaSig = QtCore.pyqtSignal(object)
    statusSig = QtCore.pyqtSignal(object)

    def __init__(self):
        super(Win, self).__init__()
        #Alll of the settings
        self.settings = dict()
        self.settings['saveLoc'] = ''
        self.settings['resSaveName'] = ''
        self.settings['phaSaveName'] = ''
        self.settings['saveComments'] = ''
        self.settings['kGPIB'] = 'Fake'
        self.settings['sGPIB'] = 'Fake'
        self.settings['measurePhase'] = False
        self.settings['measureReverse'] = False
        self.settings['stepSleep'] = 0.2
        self.settings['kCompliance'] = 1e-3
        self.settings['seriesResistance'] = 10e6
        self.settings['GPIBChoices'] = []

        self.openKeith()
        self.openSR830()
        self.initUI()

        self.startV = self.parseInp(self.ui.tGateStart.text())
        self.stepV = self.parseInp(self.ui.tGateStep.text())
        self.endV = self.parseInp(self.ui.tGateEnd.text())
        self.measureEvery = int(self.parseInp(self.ui.tMeasureEvery.text()))

        self.statusSig.connect(self.updateStatusBar)
        self.resSig.connect(self.updateResistance)
        self.phaSig.connect(self.updatePhase)

        self.resistances = np.empty((0, 2))
        self.phases = np.empty((0, 2))
        self.voltage = 0
        self.runFlag = False
        self.show()

    def initUI(self):
        #Import ui file from designer
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #initialize plot
        self.rGraph = self.ui.gResistance.plot(pen='k')
        #        self.ui.gResistance.setBackground('w')
        #        self.ui.gResistance.setForegroundBrush(pg.mkBrush('k'))
        #        self.ui.gResistance.setBackgroundBrush(pg.mkBrush('k'))
        self.p1 = self.ui.gResistance.plotItem
        self.p1.setLabel('top', text='Resistance')
        self.p1.setLabel('left', text='Resistance', units='O')
        self.p1.setLabel('bottom', text='voltage', units='V')

        #http://bazaar.launchpad.net/~luke-campagnola/pyqtgraph/inp/view/head:/examples/MultiplePlotAxes.py
        #Need to do all this nonsense to make it plot on two different axes.
        #Also note the self.updatePhase plot which shows how to update the data.
        self.p2 = pg.ViewBox()
        self.p1.showAxis('right')
        self.p1.scene().addItem(self.p2)
        self.p1.getAxis('right').linkToView(self.p2)
        self.p2.setXLink(self.p1)
        self.p1.getAxis('right').setLabel('Phase',
                                          units='deg',
                                          color='#ff0000')
        self.pGraph = pg.PlotCurveItem(pen='r')
        self.p2.addItem(self.pGraph)

        #need to set it up so that when the window (and thus main plotItem) is
        #resized, it informs the ViewBox for the second plot that it must update itself.
        self.p1.vb.sigResized.connect(
            lambda: self.p2.setGeometry(self.p1.vb.sceneBoundingRect()))

        #Connect all the things
        self.ui.bStartScan.clicked.connect(self.startScan)
        self.ui.bAbortScan.clicked.connect(self.abortScan)
        self.ui.bAbortScan.setEnabled(False)
        self.ui.bSaveData.clicked.connect(self.saveData)
        self.ui.bResetData.clicked.connect(self.resetData)

        self.ui.mFileExit.triggered.connect(self.closeEvent)
        self.ui.mFileSettings.triggered.connect(self.launchSettings)

        self.ui.tGateStart.textAccepted.connect(self.acceptTextChanges)
        self.ui.tGateStep.textAccepted.connect(self.acceptTextChanges)
        self.ui.tGateEnd.textAccepted.connect(self.acceptTextChanges)
        self.ui.tMeasureEvery.textAccepted.connect(self.acceptTextChanges)

    def acceptTextChanges(self, value):
        if type(value) is bool:
            self.statusSig.emit('Invalid Value')

    def closeEvent(self, event):
        self.abortScan()
        self.keith.close()
        self.SR830.close()
        self.close()

    def launchSettings(self):
        try:
            res = list(visa.ResourceManager().list_resources())
            res = [i.encode('ascii') for i in res]
        except:
            self.statusSig.emit(['Error loading GPIB list', 5000])
            res = ['a', 'b', 'c']
        res.append('Fake')
        self.settings['GPIBChoices'] = res

        #need to pass a copy of the settings. Otherwise it passes the reference,
        #thus changing the values and we're unable to see whether things have changed.
        newSettings, ok = SettingsDialog.getSettings(self,
                                                     copy.copy(self.settings))
        if not ok:
            print 'canceled'
            return

        #Need to check to see if the GPIB values changed so we can update them.
        #The opening procedure opens a fake isntrument if things go wrong, which
        #means we can't assign the settings dict after calling openKeith() as that would
        #potentially overwrite if we needed to open a fake instr.
        #
        #We get the old values before updating the settings. Th

        oldkGPIB = self.settings['kGPIB']
        oldsGPIB = self.settings['sGPIB']

        if self.settings["kCompliance"] != newSettings['kCompliance']:
            self.keith.setCompliance(newSettings['kCompliance'])
        self.settings = newSettings
        print oldkGPIB, newSettings['kGPIB']
        if not oldkGPIB == newSettings['kGPIB']:
            self.keith.close()
            self.settings['kGPIB'] = newSettings['kGPIB']
            self.openKeith()
        print oldsGPIB, newSettings['sGPIB']
        if not oldsGPIB == newSettings['sGPIB']:
            self.SR830.close()
            self.settings['sGPIB'] = newSettings['sGPIB']
            self.openSR830()

    def openKeith(self):
        try:
            self.keith = Keithley2400Instr(
                self.settings['kGPIB'],
                compliance=self.settings['kCompliance'])
            print 'Keithley opened'
        except:
            print 'Error opening Keithley. Adding Fake'
            self.settings['kGPIB'] = 'Fake'
            self.keith = Keithley2400Instr(
                self.settings['kGPIB'],
                compliance=self.settings['kCompliance'])

    def openSR830(self):
        try:
            self.SR830 = SR830Instr(self.settings['sGPIB'])
            print 'SR830 opened'
        except:
            print 'Error opening SR830. Adding Fake'
            self.settings['sGPIB'] = 'Fake'
            self.SR830 = SR830Instr(self.settings['sGPIB'])

    def parseInp(self, inp):
        ret = None
        #see if we can just turn it into a number and leave if we can
        try:
            ret = float(inp)
            return ret
        except:
            pass
        #tests to see whether digit is whole number or decimal, and if it has
        #some modifier at the end
        toMatch = re.compile('-?(\d+\.?\d*|\d*\.\d+)(m|u|n|M|k)?\Z')
        if re.match(toMatch, inp):
            convDict = {'m': 1e-3, 'u': 1e-6, 'n': 1e-9, 'M': 1e6, 'k': 1e3}
            try:
                ret = (
                    float(inp[:-1]) *  #convert first part to number
                    convDict[[b for b in convDict.keys() if b in inp][0]]
                )  #and multiply by the exponential
                return ret
            except:
                print 'uh oh'
        else:
            raise TypeError('Error with input', str(inp))

    def startScan(self):
        #test inputs
        try:
            self.startV = self.parseInp(self.ui.tGateStart.text())
            self.ui.tGateStart.setText(str(self.startV))
            self.stepV = self.parseInp(self.ui.tGateStep.text())
            self.ui.tGateStep.setText(str(self.stepV))
            self.endV = self.parseInp(self.ui.tGateEnd.text())
            self.ui.tGateEnd.setText(str(self.endV))
            m = self.parseInp(self.ui.tMeasureEvery.text())
            self.measureEvery = int(m)
        except Exception as e:
            self.ui.statusbar.showMessage(
                'Error converting input: {}'.format(e[1]), 3000)
            return
        if (self.endV - self.startV) * self.stepV < 0:
            self.ui.statusbar.showMessage('Incorrect step size', 3000)
            return
        #disable all the buttons and inputs so they don't get changed and confuse the user
        self.ui.bStartScan.setEnabled(False)
        self.ui.bAbortScan.setEnabled(True)
        self.ui.tGateStart.setEnabled(False)
        self.ui.tGateStep.setEnabled(False)
        self.ui.tGateEnd.setEnabled(False)
        self.ui.tMeasureEvery.setEnabled(False)
        self.ui.mFileSettings.setEnabled(False)

        #Start the thread to take the data
        self.runFlag = True
        self.scanningThread = threading.Thread(target=self.runScan,
                                               args=(self.startV, self.stepV,
                                                     self.endV))
        self.scanningThread.start()


#        self.scanningThread = QtCore.QThread(target=self.runScan, args = (start, step, end))
#        self.scanningThread.finished.connect(self.enableStart)
#        self.scanningThread.start()
#        self.scanningThread = WorkTh(target=self.runScan, args = (start, step, end), parent = self)
#        self.scanningThread.finished.connect(self.enableStart)
#        self.scanningThread.run()

    def enableStart(self):
        self.ui.bStartScan.setEnabled(True)
        self.statusSig.emit('Scan Finished')
        self.abortScan()

    def abortScan(self):
        #Re-enable all of the buttons/inputs
        self.ui.bAbortScan.setEnabled(False)
        self.ui.tGateStart.setEnabled(True)
        self.ui.tGateStep.setEnabled(True)
        self.ui.tGateEnd.setEnabled(True)
        self.ui.tMeasureEvery.setEnabled(True)
        self.ui.mFileSettings.setEnabled(True)
        if self.runFlag:
            self.runFlag = False
            self.statusSig.emit('Aborting...')

    def runScan(self, *args):
        print 'run', args
        start = args[0]
        step = args[1]
        end = args[2]
        voltageRange = np.arange(start, end, step)
        voltageRange = np.append(voltageRange, end)

        self.keith.turnOn()
        print 'turned on'

        self.referenceVoltage = self.SR830.getRefVolt()
        self.appliedCurrent = self.referenceVoltage / self.settings[
            'seriesResistance']

        if not start == 0:
            print 'not equal'
            startStep = step
            if start * step < 0:
                startStep = -step
            for voltage in np.arange(0, start, startStep):
                if not self.runFlag:
                    break
                self.doRamp(voltage)
        else:
            print 'equal'

        measureCount = self.measureEvery

        for voltage in voltageRange:
            #Make sure the main thread didn't abort the run
            if not self.runFlag:
                break
            measureCount = measureCount - 1
            if measureCount == 0 or voltage == voltageRange[0]:
                measureCount = self.measureEvery
                if not self.doMeasurementPoint(voltage):
                    print 'Error: Time out?'
                    continue
            else:
                self.doRamp(voltage)

        if self.settings['measureReverse']:
            for voltage in voltageRange[::-1]:
                #Make sure the main thread didn't abort the run
                if not self.runFlag:
                    break
                measureCount = measureCount - 1
                if measureCount == 0 or voltage == voltageRange[0]:
                    measureCount = self.measureEvery
                    if not self.doMeasurementPoint(voltage):
                        print 'Error: Time out?'
                        continue
                else:
                    self.doRamp(voltage)

        for voltage in np.arange(self.voltage, 0,
                                 -abs(step) * np.sign(self.voltage)):
            self.doRamp(voltage)

        self.keith.setVoltage(0)
        self.keith.turnOff()
        self.ui.bStartScan.setEnabled(True)
        self.statusSig.emit('Scan Finished')
        self.abortScan()

    def doRamp(self, voltage):
        self.voltage = voltage
        self.keith.setVoltage(voltage)
        time.sleep(self.settings['stepSleep'] / 10)
        self.statusSig.emit('Ramping. Voltage: ' + str(voltage))

    def doMeasurementPoint(self, voltage, reverse=False):
        self.voltage = voltage
        self.statusSig.emit('Measuring. Voltage: ' + str(voltage))
        self.keith.setVoltage(voltage)
        ret = False
        time.sleep(self.settings['stepSleep']
                   )  #Sleep incase there's a lag between updating the scope
        if self.settings['measurePhase']:
            #returns the magnitude of the measured voltage and the phase
            val = self.SR830.getMultiple('r', 't')
            if not val:
                return ret
            ret = True
            r = val[0]
            t = val[1]
            res = r / self.appliedCurrent
            self.resSig.emit([[voltage, res]])
            self.phaSig.emit([[voltage, t]])
        else:
            r = self.SR830.getChannel('r')
            if not r:
                return ret
            ret = True
            res = r / self.appliedCurrent
            self.resSig.emit([[voltage, res]])
        return ret

    def saveData(self):
        fname = str(
            QtGui.QFileDialog.getSaveFileName(
                self,
                "Resistance Save File...",
                directory=self.settings['saveLoc']))
        if not fname == '':
            directory = fname[:-fname[::-1].find('/')]
            self.settings['saveLoc'] = directory
            np.savetxt(fname,
                       self.resistances,
                       header=self.genSaveHeader() +
                       '\nGate (V), Resistance (Ohms)')
        if self.settings['measurePhase']:
            fname = str(
                QtGui.QFileDialog.getSaveFileName(
                    self,
                    "Phase Save File...",
                    directory=self.settings['saveLoc']))
            if not fname == '':
                directory = fname[:-fname[::-1].find('/')]
                self.settings['saveLoc'] = directory
                np.savetxt(fname,
                           self.phases,
                           header=self.genSaveHeader() +
                           '\nGate (V), Phase (deg)')

    def genSaveHeader(self):
        st = 'Time between steps(s): ' + str(self.settings['stepSleep'])
        st += '\nStep size(V): ' + str(self.stepV)
        st += '\nMeasured every: ' + str(self.measureEvery)
        st += '\nCompliance(A): ' + str(self.settings['kCompliance'])
        st += '\nSeries Resistor(Ohms): ' + str(
            self.settings['seriesResistance'])
        st += '\n' + self.settings['saveComments']
        return st

    def resetData(self):
        self.resistances = np.empty((0, 2))
        self.rGraph.setData([], [])
        self.phases = np.empty((0, 2))
        self.pGraph.setData([], [])

    def updateStatusBar(self, args):
        '''function to update the status bar. Connects to a signal so it
           can be used from different threads. Pass a string to emit a message for
           3 seconds. Else pass a list, the first element the message and the second
           a ms value for the timeout'''
        if type(args) is str:
            self.ui.statusbar.showMessage(args, 3000)
        else:
            self.ui.statusbar.showMessage(args[0], args[1])

    def updateResistance(self, data):
        self.resistances = np.append(self.resistances, data, axis=0)
        self.rGraph.setData(self.resistances)

    def updatePhase(self, data):
        self.phases = np.append(self.phases, data, axis=0)
        self.pGraph.setData(self.phases[:, 0], self.phases[:, 1])
        self.p2.setGeometry(self.p1.vb.sceneBoundingRect())
class MyMainWindow(Ui_MainWindow):

    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__()
        # QtGui.QMainWindow.__init__(self,parent)
        self.ui = Ui_MainWindow(self)
        self.ui.setupUi(self)
        self.setupConnect()
        self.start_bind = False
        self.start_answer = False

    def setupConnect(self):
        self.ui.pushButton.clicked.connect(self.answer)
        self.ui.pushButton_bind.clicked.connect(self.bind)

    def answer(self):
        if not self.start_answer:
            self.ui.pushButton.setText('清除')
            self.host = ''
            self.port = 12345
            self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            self.s.bind((self.host, self.port))
            while True:
                try:
                    msg, addr = self.s.recvfrom(8)
                    print("Receive data from:", addr)
                    team_name = team_ip_record[str(addr[0])]
                    print('1')
                    print(team_name)
                    self.ui.label_team_got.setText(team_name)
                    print('2')
                    self.start_answer = True
                    print('Done')
                    break
                except:
                    pass
            self.s.close()
        else:
            self.ui.pushButton.setText('开始抢答!!')
            self.ui.label_team_got.setText('')
            self.start_answer = False

    def bind(self):
        if not self.start_bind:
            print('start bind')
            self.start_bind = True
            self.ui.pushButton_bind.setText('停止绑定')
            self.myBindThread = BindThread()
            self.myBindThread.myCommunicator.trigger.connect(self.updateName)
            self.myBindThread.start()
        else:
            self.start_bind = False
            self.ui.pushButton_bind.setText('开始绑定')
            self.myBindThread.stop()

    def updateName(self):
        try:
            self.ui.label_1.setText(team_name_list[0])
            self.ui.label_2.setText(team_name_list[1])
            self.ui.label_3.setText(team_name_list[2])
            self.ui.label_4.setText(team_name_list[3])
            self.ui.label_5.setText(team_name_list[4])
            self.ui.label_6.setText(team_name_list[5])
            self.ui.label_7.setText(team_name_list[6])
        except:
            pass
Beispiel #13
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)