示例#1
0
  def OnExtractFiber(self):
    if self.classList.currentIndex == 0 or self.classList.currentIndex == 0:
      msg = qt.QMessageBox()
      msg.setIcon(3)
      msg.setText("You must choose the type and the class you want to extract from the current fiber")
      msg.exec_()
    elif self.disROI.isChecked():
      msg = qt.QMessageBox()
      msg.setIcon(3)
      msg.setText("ROI is disable, please choose Positive or Negative region to extract")
      msg.exec_()
    else:
      nameNode = self.fiberList.itemText(self.fiberList.currentIndex)

      self.ROISelector.FiberBundleFromSelection.addNode()
      nodeID = self.ROISelector.FiberBundleFromSelection.currentNode().GetID()
      if self.classList.currentIndex == 1:
        self.nodeNegDict[nameNode].append(nodeID)
        numExtract = len(self.nodeNegDict[nameNode])
        self.ROISelector.FiberBundleFromSelection.currentNode().SetName(nameNode+"_negative_extracted_"+str(numExtract))
      elif self.classList.currentIndex == 2:
        self.nodePosDict[nameNode].append(nodeID)
        numExtract = len(self.nodePosDict[nameNode])
        self.ROISelector.FiberBundleFromSelection.currentNode().SetName(nameNode+"_positive_extracted_"+str(numExtract))
      logic = TraficBiLogic()
      logic.runExtractFiber(self.ROISelector, self.posROI.isChecked(), self.negROI.isChecked())

    return
示例#2
0
  def OnExtractFiber(self):
    if self.fiberList.itemText(self.fiberList.currentIndex) == "Select a type of fiber":
      msg = qt.QMessageBox()
      msg.setIcon(3)
      msg.setText("You must choose which type of fiber you want to extract from the current fiber")
      msg.exec_()
    elif self.disROI.isChecked():
      msg = qt.QMessageBox()
      msg.setIcon(3)
      msg.setText("ROI is disable, please choose Positive or Negative region to extract")
      msg.exec_()
    else:
      nameNode = self.fiberList.itemText(self.fiberList.currentIndex)
      # Process To modify the name
      
      # If not already exist 
      # self.reviewsFormLayout.addRow(reviewNode)
      # self.ROISelector.setAnnotationMRMLNodeForFiberSelection(newNode)

      # print self.ROISelector.fiberBundleNode()
      
      self.ROISelector.FiberBundleFromSelection.addNode()
      nodeID = self.ROISelector.FiberBundleFromSelection.currentNode().GetID()
      self.nodeDict[nameNode].append(nodeID)
      numExtract = len(self.nodeDict[nameNode])
      self.ROISelector.FiberBundleFromSelection.currentNode().SetName(nameNode+"_extracted_"+str(numExtract))
      
      logic = TraficMultiLogic()
      logic.runExtractFiber(self.ROISelector, self.posROI.isChecked(), self.negROI.isChecked())

    return
示例#3
0
 def saveStagesAsPreset(self, stages):
     from PythonQt import BoolResult
     ok = BoolResult()
     presetName = qt.QInputDialog().getText(qt.QWidget(), 'Save Preset',
                                            'Preset name: ',
                                            qt.QLineEdit.Normal,
                                            'my_preset', ok)
     if not ok:
         return
     if presetName in self.getPresetNames():
         qt.QMessageBox().warning(
             qt.QWidget(), 'Warning',
             presetName + ' already exists. Set another name.')
         self.saveStagesAsPreset(stages)
         return
     outFilePath = os.path.join(self.presetPath, presetName + '.json')
     saveSettings = self.getPresetParametersByName()
     saveSettings['stages'] = self.removeNodesFromStages(stages)
     try:
         with open(outFilePath, 'w') as outfile:
             json.dump(saveSettings, outfile)
     except:
         qt.QMessageBox().warning(qt.QWidget(), 'Warning',
                                  'Unable to write into ' + outFilePath)
         return
     print('Saved preset to ' + outFilePath)
     return presetName
示例#4
0
 def deviceError(self, title, message, error_type="warning"):
     deviceMBox = qt.QMessageBox()
     if error_type == "warning":
         deviceMBox.setIcon(qt.QMessageBox().Warning)
     elif error_type == "critical":
         deviceMBox.setIcon(qt.QMessageBox().Critical)
     deviceMBox.setWindowTitle(title)
     deviceMBox.setText(message)
     deviceMBox.exec()
示例#5
0
 def CheckBrowseDirectory(self, dir, name):
   if dir.text=="":
     msg = qt.QMessageBox()
     msg.setIcon(3)
     msg.setText("Please choose "+ str(name) + "")
     msg.exec_()
     return False
   elif not os.path.isdir(dir.text):
     msg = qt.QMessageBox()
     msg.setIcon(3)
     msg.setText("Unknown or non valid directory. Please correct the "+ str(name))
     msg.exec_()
     return False
   return True
示例#6
0
 def CheckInputClass(self):
   if not os.path.isfile(self.inputClass.text):
     msg = qt.QMessageBox()
     msg.setIcon(3)
     msg.setText("File doesn't exist. Please correct the input file")
     msg.exec_()
     return False
   elif self.inputClass.text.rfind(".vtk") == -1 and self.inputClass.text.rfind(".vtp") == -1:
     msg = qt.QMessageBox()
     msg.setIcon(3)
     msg.setText("Invalid File Format. Must be a .vtk or .vtp file. Please correct the input file")
     msg.exec_()
     return False
   return True
示例#7
0
  def createExtensionModule(self):
    if (self.extensionLocation is None):
      # Action shouldn't be enabled if no extension is selected, but guard
      # against that just in case...
      return

    dlg = CreateComponentDialog("module", self.parent.window())
    dlg.setTemplates(self.templateManager.templates("modules"),
                     default="scripted")
    dlg.showDestination = False

    while dlg.exec_() == qt.QDialog.Accepted:
      name = dlg.componentName

      try:
        self.templateManager.copyTemplate(self.extensionLocation, "modules",
                                          dlg.componentType, name)

      except:
        md = qt.QMessageBox(self.parent.window())
        md.icon = qt.QMessageBox.Critical
        md.text = "An error occurred while trying to create the module."
        md.detailedText = traceback.format_exc()
        md.standardButtons = qt.QMessageBox.Retry | qt.QMessageBox.Close
        if md.exec_() != qt.QMessageBox.Retry:
          return

        continue

      try:
        self.extensionProject.addModule(name)
        self.extensionProject.save()

      except:
        md = qt.QMessageBox(self.parent.window())
        md.icon = qt.QMessageBox.Critical
        md.text = "An error occurred while adding the module to the extension."
        md.informativeText = "The module has been created, but the extension" \
                             " CMakeLists.txt could not be updated. In order" \
                             " to include the module in the extension build," \
                             " you will need to update the extension" \
                             " CMakeLists.txt by hand."
        md.detailedText = traceback.format_exc()
        md.standardButtons = qt.QMessageBox.Close
        md.exec_()

      self.loadModules(os.path.join(self.extensionLocation, name), depth=0)
      return
    def onLoadTable(self):
        if hasattr(self, 'fileTable'):
            slicer.mrmlScene.RemoveNode(self.fileTable)

        with open(self.tableSelector.currentPath, "r") as file:
            paths = file.read().splitlines()

        if len(paths) >= 4:
            self.tablepath = paths[0]
            self.fileTable = slicer.util.loadNodeFromFile(
                self.tablepath, 'TableFile')
            logic = CleftLandmarkFlowLogic()
            logic.checkForStatusColumn(
                self.fileTable,
                paths[0])  # if not present adds and saves to file

            with open(paths[1], "r") as file:
                self.landmarkNames = np.array(file.read().splitlines())

            self.imagedir = paths[2]
            self.landmarkdir = paths[3]

            self.importVolumeButton.enabled = True
            self.assignLayoutDescription(self.fileTable)
            # logic.hideCompletedSamples(self.fileTable)
            self.fileTable.SetLocked(True)
            self.fileTable.GetTable().Modified()  # update table view
        else:
            msg = qt.QMessageBox()
            msg.setIcon(qt.QMessageBox.Warning)
            msg.setText("Check the contents of the project file.")
            msg.setWindowTitle("Project file error")
            msg.setStandardButtons(qt.QMessageBox.Ok)
            msg.exec_()
            self.importVolumeButton.enabled = False
 def onLeadDBSPathChanged(self):
     newDir = self.leadDBSPathButton.directory
     LeadDBSPath().setValue(newDir)
     if not os.path.isfile(os.path.join(newDir, "lead.m")):
         qt.QMessageBox().warning(
             qt.QWidget(), "Error",
             "Invalid leaddbs path. Select leaddbs root install directory")
示例#10
0
def messageBox(text, parent=None, **kwargs):
    import qt
    mbox = qt.QMessageBox(parent if parent else mainWindow())
    mbox.text = text
    for key, value in kwargs.iteritems():
        if hasattr(mbox, key):
            setattr(mbox, key, value)
    return mbox.exec_()
示例#11
0
 def CheckFiberListClass(self):
   if self.fiberListClass.currentIndex == 0:
     msg = qt.QMessageBox()
     msg.setIcon(3)
     msg.setText("Please select a type of fiber to classify")
     msg.exec_()
     return False
   return True
示例#12
0
 def showMessageBox(self, severity, message):
     # INFO severity is default, INFO is not appended to the message
     if severity == 'WARNING':
         message = 'Warning: ' + message
     elif severity == 'ERROR':
         message = 'Error: ' + message
     self.messageBox = qt.QMessageBox()
     self.messageBox.setText(message)
     self.messageBox.setModal(False)
     self.messageBox.show()
示例#13
0
 def checkdFPath(self):
   if self.dFPath.text == "":
     msg = qt.QMessageBox()
     msg.setIcon(3)
     msg.setText("Please choose a displacement field filename")
     msg.exec_()
   elif not os.path.isfile(self.dFPath.text):
     msg = qt.QMessageBox()
     msg.setIcon(3)
     msg.setText("File doesn't exist. Please correct the displacement field filename")
     msg.exec_()
     return False
   elif self.dFPath.text.rfind(".nrrd") == -1:
     msg = qt.QMessageBox()
     msg.setIcon(3)
     msg.setText("Invalid File Format. Must be a .nrrd file. Please correct the displacement field filename")
     msg.exec_()
     return False
   return True
示例#14
0
 def __init__(self, parent, helpString=""):
     self.helpString = helpString
     self.message = qt.QMessageBox()
     self.message.objectName = 'EditorHelpMessageBox'
     self.message.setWindowTitle("Editor Help")
     self.button = qt.QPushButton("?", parent)
     self.button.objectName = 'EditorHelpButton'
     self.button.setMaximumWidth(15)
     self.button.setToolTip("Bring up a help window")
     parent.layout().addWidget(self.button)
     self.button.connect('clicked()', self.showHelp)
示例#15
0
 def getValidAtlases(self):
     validAtlases = glob.glob(
         os.path.join(self.getAtlasesPath(), '*', 'atlas_index.mat'))
     if not validAtlases:
         qt.QMessageBox().warning(qt.QWidget(), "",
                                  "Invalid Lead-DBS path in preferences.")
         return []
     validAtlases = [
         os.path.basename(os.path.dirname(a)) for a in validAtlases
     ]
     validAtlases.sort()
     return validAtlases
示例#16
0
 def onProcessingStatusUpdate(self, caller, event):
     if (caller.GetStatus() & caller.Cancelled):
         self.ui.runRegistrationButton.text = "Run Registration"
         self.logic._cliNode.RemoveObserver(self._cliObserver)
     elif (caller.GetStatus() & caller.Completed):
         if (caller.GetStatus() & caller.ErrorsMask):
             qt.QMessageBox().warning(qt.QWidget(), 'Error',
                                      'ANTs Failed. See CLI output.')
         self.ui.runRegistrationButton.text = "Run Registration"
         self.logic._cliNode.RemoveObserver(self._cliObserver)
     else:
         self.ui.runRegistrationButton.text = "Cancel"
示例#17
0
 def onCloseCaseButtonClicked(self):
     if not self.session.data.completed:
         dialog = qt.QMessageBox(
             qt.QMessageBox.Question, "SliceTracker",
             "Do you want to mark this case as completed?",
             qt.QMessageBox.Yes | qt.QMessageBox.No | qt.QMessageBox.Cancel,
             slicer.util.mainWindow(), qt.Qt.WindowStaysOnTopHint).exec_()
         if dialog == qt.QMessageBox.Yes:
             self.session.complete()
         elif dialog == qt.QMessageBox.Cancel:
             return
     if self.session.isRunning():
         self.session.close(save=False)
示例#18
0
  def createExtension(self):
    dlg = CreateComponentDialog("extension", self.parent.window())
    dlg.setTemplates(self.templateManager.templates("extensions"))

    while dlg.exec_() == qt.QDialog.Accepted:
        
        # If the selected destination is in a repository then use the root of that repository
        # as destination
      try:
        repo = SlicerWizard.Utilities.getRepo(dlg.destination)

        createInSubdirectory = True
        requireEmptyDirectory = True
        
        if repo is None:
          destination = os.path.join(dlg.destination, dlg.componentName)
          if os.path.exists(destination):
            raise IOError("create extension: refusing to overwrite"
                          " existing directory '%s'" % destination)
          createInSubdirectory = False

        else:
          destination = SlicerWizard.Utilities.localRoot(repo)
          cmakeFile = os.path.join(destination, "CMakeLists.txt")
          createInSubdirectory = False # create the files in the destination directory
          requireEmptyDirectory = False # we only check if no CMakeLists.txt file exists
          if os.path.exists(cmakeFile):
            raise IOError("create extension: refusing to overwrite"
                          " directory containing CMakeLists.txt file at '%s'" % dlg.destination)

        path = self.templateManager.copyTemplate(
                 destination, "extensions",
                 dlg.componentType, dlg.componentName,
                 createInSubdirectory, requireEmptyDirectory)

      except:
        md = qt.QMessageBox(self.parent.window())
        md.icon = qt.QMessageBox.Critical
        md.text = "An error occurred while trying to create the extension."
        md.detailedText = traceback.format_exc()
        md.standardButtons = qt.QMessageBox.Retry | qt.QMessageBox.Close
        if md.exec_() != qt.QMessageBox.Retry:
          return

        continue

      if self.selectExtension(path):
        self.editExtensionMetadata()

      return
    def onImportMesh(self):
        logic = CleftLandmarkFlowLogic()
        self.objpath, mtlpath, texdir = logic.getActiveCell(self.fileTable)

        if bool(self.objpath):

            print(self.objpath + " " + mtlpath + " " + texdir)
            self.meshNode, self.textureNode = logic.applyMultiTexture(
                os.path.join(self.imagedir, self.objpath),
                os.path.join(self.imagedir, mtlpath),
                os.path.join(self.imagedir, texdir))
            if bool(self.meshNode):
                # self.startSegmentationButton.enabled = True
                self.activeRow = logic.getActiveCellRow()
                # self.updateStatus(self.activeRow, 'Processing') # TODO uncomment this

                # TODO Texture

                # fiducials
                fiducialName = os.path.splitext(self.objpath)[0]
                fiducialOutput = os.path.join(self.landmarkdir,
                                              fiducialName + '.fcsv')
                print(fiducialOutput)
                try:
                    print("Loading fiducial")
                    a = slicer.util.loadMarkupsFiducialList(fiducialOutput)
                    self.fiducialNode = a[1]
                except:
                    print("failed loading fiducial")
                    self.fiducialNode = slicer.mrmlScene.AddNewNodeByClass(
                        "vtkMRMLMarkupsFiducialNode", 'F')
                # print(self.fiducialNode)
                # print(self.fiducialNode.GetNumberOfControlPoints())
                # slicer.util.selectModule('Markups')

                self.enableButtons()

            else:
                msg = qt.QMessageBox()
                msg.setIcon(qt.QMessageBox.Warning)
                msg.setText("Image \"" + self.objpath +
                            "\" is not in folder \"" + self.imagedir + ".")
                msg.setWindowTitle("Image cannot be loaded")
                msg.setStandardButtons(qt.QMessageBox.Ok)
                msg.exec_()
                logging.debug("Error loading associated files.")

        else:
            logging.debug("No valid table cell selected.")
示例#20
0
 def __init__(self, parent=None):
   ScriptedLoadableModuleWidget.__init__(self, parent)
   self.logic = SlicerCaseManagerLogic()
   self.moduleName = "slicerCaseManager"
   #self.modulePath = os.path.dirname(slicer.util.modulePath(self.moduleName))
   self._caseRootDir = self.getSetting('CasesRootLocation')
   self._currentCaseDirectory = None
   self._caseDirectoryList = {}
   self.caseDirectoryList = {"DICOM/Planning", "Results"}
   self.warningBox = qt.QMessageBox()
   self.CloseCaseEvent = vtk.vtkCommand.UserEvent + 201
   self.LoadCaseCompletedEvent = vtk.vtkCommand.UserEvent + 202
   self.StartCaseImportEvent = vtk.vtkCommand.UserEvent + 203
   self.CreatedNewCaseEvent = vtk.vtkCommand.UserEvent + 204
   self.setup()
示例#21
0
    def updateParameterNodeFromGUI(self, caller=None, event=None):
        """
    This method is called when the user makes any change in the GUI.
    The changes are saved into the parameter node (so that they are restored when the scene is saved and loaded).
    """

        if self._parameterNode is None or self._updatingGUIFromParameterNode:
            return

        currentInputNode = self.ui.inputSelector.currentNode()
        if isinstance(currentInputNode, slicer.vtkMRMLTransformNode):
            if not (isinstance(currentInputNode.GetTransformFromParent(),
                               slicer.vtkOrientedGridTransform)
                    or isinstance(currentInputNode.GetTransformToParent(),
                                  slicer.vtkOrientedGridTransform)):
                qt.QMessageBox().warning(
                    qt.QWidget(), "",
                    "Select a Transform Node containing a Grid Transform")
                return

        wasModified = self._parameterNode.StartModify(
        )  # Modify all properties in a single batch

        self._parameterNode.SetNodeReferenceID(
            "InputNode", self.ui.inputSelector.currentNodeID)
        self._parameterNode.SetNodeReferenceID(
            "SourceFiducial", self.ui.sourceFiducialsComboBox.currentNodeID)
        self._parameterNode.SetNodeReferenceID(
            "TargetFiducial", self.ui.targetFiducialsComboBox.currentNodeID)
        self._parameterNode.SetNodeReferenceID(
            "OutputGridTransform", self.ui.outputSelector.currentNodeID)
        self._parameterNode.SetParameter(
            "DrawMode",
            next(filter(lambda a: a.checked,
                        self.ui.drawModeMenu.actions())).text)
        self._parameterNode.SetParameter("Radius",
                                         "%.2f" % self.ui.radiusSlider.value)
        self._parameterNode.SetParameter("Stiffness",
                                         str(self.ui.stiffnessSpinBox.value))
        # spacing
        if self.ui.spacingSameAsInputCheckBox.checked:
            size, origin, spacing = GridNodeHelper.getGridDefinition(
                currentInputNode)
        else:
            spacing = [self.ui.spacingSpinBox.value]
        self._parameterNode.SetParameter("Spacing", str(spacing[0]))

        self._parameterNode.EndModify(wasModified)
示例#22
0
 def updateStimulationTransform(self):
     if not self.logic.VTASource:
         return
     # get current active stim
     N = next(
         filter(
             lambda n: getattr(self.ui, 'METoolButton_' + str(n)).actions()[
                 1].checked, range(9)), None)
     if N is None or N not in self.logic.trajectories.keys():
         self.ui.stimulationActiveCheckBox.checked = False
         qt.QMessageBox().warning(qt.QWidget(), '',
                                  'Set a Stimulation Source')
         return
     # set transform
     self.logic.VTASource.SetAndObserveTransformNodeID(
         self.logic.trajectories[N].translationTransform.GetID())
示例#23
0
 def killOtherListeners(self, osName, pid=None):
     msgBox = qt.QMessageBox()
     msgBox.setText(
         'There are other DICOM listeners running.\n Do you want to end them?'
     )
     msgBox.setStandardButtons(qt.QMessageBox.Yes | qt.QMessageBox.No)
     val = msgBox.exec_()
     if (val == qt.QMessageBox.Yes):
         if osName == 'nt':
             os.popen('taskkill /f /im storescp.exe')
         elif osName == 'posix':
             import signal
             os.kill(pid, signal.SIGKILL)
         return True
     else:
         return False
示例#24
0
def queryUserApproveSubject(subjectPath):
  msgBox = qt.QMessageBox()
  msgBox.setText('No corrections made')
  msgBox.setInformativeText('Save subject as approved?')
  msgBox.setStandardButtons(qt.QMessageBox().Save | qt.QMessageBox().Discard | qt.QMessageBox().Cancel)
  ret = msgBox.exec_()
  if ret == qt.QMessageBox().Cancel:
    return False
  if ret == qt.QMessageBox().Save:
    saveApprovedData(subjectPath)
  return True
    def onExportLandmarks(self):
        if hasattr(self, 'fiducialNode'):
            for i in range(0, self.fiducialNode.GetNumberOfControlPoints()):
                self.fiducialNode.SetNthFiducialLabel(i, self.landmarkNames[i])

            fiducialName = os.path.splitext(self.objpath)[0]
            fiducialOutput = os.path.join(self.landmarkdir,
                                          fiducialName + '.fcsv')
            if slicer.util.saveNode(self.fiducialNode, fiducialOutput):
                self.updateTableAndGUI()
            else:
                msg = qt.QMessageBox()
                msg.setIcon(qt.QMessageBox.Warning)
                msg.setText("Cannot save the landmark file.")
                msg.setWindowTitle("Landmark file cannot be saved")
                msg.setStandardButtons(qt.QMessageBox.Ok)
                # msg.buttonClicked.connect(msgbtn)
                msg.exec_()
示例#26
0
    def __init__(self, atlasPath):

        try:
            import h5py
        except:
            slicer.util.pip_install('h5py')
            import h5py

        with h5py.File(atlasPath, 'r') as atlasFile:
            names = self.readNames(atlasFile)
            colors = self.readColors(atlasFile)
            types = self.readTypes(atlasFile)
            showIndex = self.readShowIndex(atlasFile)
            pixdimTypes = self.readPixdimType(atlasFile)

        self.structures = []

        for i, pixdimType in enumerate(pixdimTypes):
            if pixdimType == 'numeric':
                structure = ModelStructure()
            elif pixdimType == 'fibers':
                structure = FibersStructure()
            elif pixdimType == 'discfibers':
                structure = DiscFibersStructure()
            if isinstance(structure, FibersStructure) and not hasattr(
                    slicer.modules, 'tractographydisplay'):
                qt.QMessageBox().warning(
                    qt.QWidget(), "Error",
                    "Install SlicerDMRI Extension to load fiber atlases")
                continue
            structure.atlasPath = atlasPath
            structure.index = i
            structure.name = names[i]
            structure.color = colors[i]
            structure.type = types[i]
            structure.visibility = i in showIndex
            self.structures.append(structure)
示例#27
0
 def onAddButton(self):
     leadDBSPath = slicer.util.settingsValue(
         "NetstimPreferences/leadDBSPath", "", converter=str)
     if leadDBSPath == "":
         qt.QMessageBox().warning(
             qt.QWidget(), "", "Add Lead-DBS path to Slicer preferences")
         return
     validAtlasesNames = ImportAtlas.ImportAtlasLogic().getValidAtlases()
     if not validAtlasesNames:
         return
     result = BoolResult()
     atlasName = qt.QInputDialog.getItem(qt.QWidget(), 'Select Atlas', '',
                                         validAtlasesNames, 0, 0, result)
     if result:
         qt.QApplication.setOverrideCursor(qt.Qt.WaitCursor)
         qt.QApplication.processEvents()
         try:
             ImportAtlas.ImportAtlasLogic().readAtlas(
                 os.path.join(
                     ImportAtlas.ImportAtlasLogic().getAtlasesPath(),
                     atlasName, 'atlas_index.mat'))
         finally:
             qt.QApplication.restoreOverrideCursor()
     self.updateTable()
示例#28
0
    def onStartStopDicomPeer(self, flag):
        if flag:
            import os
            self.startStopDicomPeerButton.setEnabled(False)
            dicomFilesDirectory = slicer.app.temporaryPath
            configFilePath = dicomFilesDirectory + '/Dcmtk-db/dcmqrscp.cfg'
            processCurrentPath = dicomFilesDirectory + '/Dcmtk-db/'

            msgBox = qt.QMessageBox()
            msgBox.setText(
                'Do you want to choose local DCMTK database folder?')
            msgBox.setStandardButtons(qt.QMessageBox.Yes | qt.QMessageBox.No)
            val = msgBox.exec_()
            if (val == qt.QMessageBox.Yes):
                print 'Yes'
                dicomFilesDirectory = qt.QFileDialog.getExistingDirectory(
                    None, 'Select DCMTK database folder')
                configFilePath = dicomFilesDirectory + '/dcmqrscp.cfg'
                processCurrentPath = dicomFilesDirectory
            else:
                downloads = (
                    ('http://slicer.kitware.com/midas3/download?items=18822',
                     'Dcmtk-db.zip'), )
                print 'Downloading'

                import urllib
                for url, name in downloads:
                    filePath = slicer.app.temporaryPath + '/' + name
                    if not os.path.exists(filePath) or os.stat(
                            filePath).st_size == 0:
                        print 'Requesting download %s from %s...\n' % (name,
                                                                       url)
                        urllib.urlretrieve(url, filePath)
                print 'Finished with download'

                print 'Unzipping'
                qt.QDir().mkpath(dicomFilesDirectory)
                slicer.app.applicationLogic().Unzip(filePath,
                                                    dicomFilesDirectory)

            import subprocess
            dcmqrscpExeOptions = (
                '/bin',
                '/../CTK-build/CMakeExternals/Install/bin',
                '/../DCMTK-install/bin',
                '/../DCMTK-build/bin',
            )

            dcmqrscpExePath = None
            dcmqrscpExeName = '/dcmqrscp'
            if slicer.app.os == 'win':
                dcmqrscpExeName = dcmqrscpExeName + '.exe'
            for path in dcmqrscpExeOptions:
                testPath = slicer.app.slicerHome + path + dcmqrscpExeName
                if os.path.exists(testPath):
                    dcmqrscpExePath = testPath
                    break
            if not dcmqrscpExePath:
                raise (UserWarning("Could not find dcmqrscp executable"))

            args = (dcmqrscpExePath, '-c', configFilePath)
            print 'Start DICOM peer'
            self.popen = subprocess.Popen(args,
                                          stdout=subprocess.PIPE,
                                          cwd=processCurrentPath)
            self.startStopDicomPeerButton.setEnabled(True)
        else:
            print 'Stop DICOM peer'
            self.popen.kill()
示例#29
0
def display_error(message):
    mb = qt.QMessageBox()
    mb.setText(message)
    mb.setStandardButtons(mb.Ok)
    mb.setDefaultButton(mb.Ok)
    mb.exec_()
示例#30
0
 def confirmOrSaveDialog(message, title='mpReview'):
     box = qt.QMessageBox(qt.QMessageBox.Question, title, message)
     box.addButton("Exit, discard changes", qt.QMessageBox.AcceptRole)
     box.addButton("Save changes", qt.QMessageBox.ActionRole)
     box.addButton("Cancel", qt.QMessageBox.RejectRole)
     return box.exec_()