def __init__(self, parent=None): # initialization of Qt MainWindow widget super(PyqtgraphGraphicsWidget, self).__init__(parent) # # set the "canvas" to the RawImage widget # self.rawImg = RawImageWidget(QWidget()) # # create a vertical box layout # self.vbl = QVBoxLayout() # # add widget to vertical box # self.vbl.addWidget(self.rawImg) # # set the layout to the vertical box # self.setLayout(self.vbl) # Create a central Graphics Layout Widget self.widget = GraphicsLayoutWidget() # self.setCentralWidget(self.win) # A plot area (ViewBox + axes) for displaying the image self.p1 = self.widget.addPlot() # Item for displaying image data self.img = ImageItem() self.p1.addItem(self.img) # create a vertical box layout self.vbl = QVBoxLayout() # add widget to vertical box self.vbl.addWidget(self.widget) # set the layout to the vertical box self.setLayout(self.vbl)
def setupUserInterface(self): """ Initialise the User Interface """ # Left frame leftFrame = QtGui.QFrame() leftFrameLayout = QtGui.QHBoxLayout() leftFrame.setLayout(leftFrameLayout) leftFrame.setLineWidth(0) leftFrame.setFrameStyle(QtGui.QFrame.Panel) leftFrameLayout.setContentsMargins(0,0,5,0) # Left frame contents self.viewMain = GraphicsLayoutWidget() # A GraphicsLayout within a GraphicsView leftFrameLayout.addWidget(self.viewMain) self.viewMain.setMinimumSize(200,200) self.vb = MultiRoiViewBox(lockAspect=True,enableMenu=True) self.viewMain.addItem(self.vb) self.vb.disableAutoRange() # Right frame self.sidePanel = SidePanel(self) # UI window (containing left and right frames) UIwindow = QtGui.QWidget(self) UIwindowLayout = QtGui.QHBoxLayout() UIwindowSplitter = QtGui.QSplitter(QtCore.Qt.Horizontal) UIwindowLayout.addWidget(UIwindowSplitter) UIwindow.setLayout(UIwindowLayout) self.setCentralWidget(UIwindow) UIwindowSplitter.addWidget(leftFrame) UIwindowSplitter.addWidget(self.sidePanel) # Application window self.setWindowTitle('BMDanalyse') self.setWindowIcon(self.icons['BMDanalyseIcon']) self.setMinimumSize(600,500) self.resize(self.minimumSize()) # Window menus self.createMenus() self.createActions()
def __init__(self, width, height, hAxisCtrl, vAxisCtrl): self.__window = GraphicsLayoutWidget() self.__window.resize(width, height) self.__window.move(0, 0) self.__window.setFocusPolicy(Qt.StrongFocus) self.__window.setObjectName("plotWindow") self.__window.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowMinimizeButtonHint) self.__window.show() plot = self.__window.addPlot(0, 0, 1, 1, enableMenu=False) self.__mainPlot = MainPlot(plot, hAxisCtrl, vAxisCtrl) waveLayout = self.__window.addLayout(0, 1, 1, 1) self.__wavePlots = WavePlots(waveLayout) self.__window.ci.layout.setColumnStretchFactor(0, 80) self.__window.ci.layout.setColumnStretchFactor(1, 20)
def __init__(self, *args, **kwargs): ''' Constructor ''' View.__init__(self, *args, **kwargs) widget = GraphicsLayoutWidget() self._viewBox = widget.addViewBox(lockAspect=True, invertY=True) self._imgItem = CustomImageItem() self._viewBox.addItem(self._imgItem) self.addWidget(widget) self.setTitle("Lensed Image") self._imgItem.sigPressed.connect(self.pressed_slot) self._imgItem.sigDragged.connect(self.dragged_slot) self._imgItem.sigReleased.connect(self.released_slot) self.roiStart = None self.roiEnd = None self.dragStarted = False self._roi = None self.addSignals(ROI_set=self._sigROISet)
def setupUserInterface(self): """ Initialise the User Interface """ # Left frame leftFrame = QtGui.QFrame() leftFrameLayout = QtGui.QHBoxLayout() leftFrame.setLayout(leftFrameLayout) leftFrame.setLineWidth(0) leftFrame.setFrameStyle(QtGui.QFrame.Panel) leftFrameLayout.setContentsMargins(0, 0, 5, 0) # Left frame contents self.viewMain = GraphicsLayoutWidget( ) # A GraphicsLayout within a GraphicsView leftFrameLayout.addWidget(self.viewMain) self.viewMain.setMinimumSize(200, 200) self.vb = MultiRoiViewBox(lockAspect=True, enableMenu=True) self.viewMain.addItem(self.vb) self.vb.disableAutoRange() # Right frame self.sidePanel = SidePanel(self) # UI window (containing left and right frames) UIwindow = QtGui.QWidget(self) UIwindowLayout = QtGui.QHBoxLayout() UIwindowSplitter = QtGui.QSplitter(QtCore.Qt.Horizontal) UIwindowLayout.addWidget(UIwindowSplitter) UIwindow.setLayout(UIwindowLayout) self.setCentralWidget(UIwindow) UIwindowSplitter.addWidget(leftFrame) UIwindowSplitter.addWidget(self.sidePanel) # Application window self.setWindowTitle('BMDanalyse') self.setWindowIcon(self.icons['BMDanalyseIcon']) self.setMinimumSize(600, 500) self.resize(self.minimumSize()) # Window menus self.createMenus() self.createActions()
class GraphicsWidget(QWidget): """Widget defined in Qt Designer""" def __init__(self, parent=None): # initialization of widget super(GraphicsWidget, self).__init__(parent) # Create a central Graphics Layout Widget self.widget = GraphicsLayoutWidget() # A plot area (ViewBox + axes) for displaying the image self.p1 = self.widget.addPlot() # Item for displaying an array of image data stacks self.stacks = [] img = ImageItem() self.p1.addItem(img) self.stacks.append(img) # create a vertical box layout self.vbl = QVBoxLayout() # add widget to vertical box self.vbl.addWidget(self.widget) # set the layout to the vertical box self.setLayout(self.vbl) # Levels/color control with a histogram # self.hist = HistogramLUTWidget() # self.hist.setImageItem(self.img) # parent.horizontalLayout_View.addWidget(self.hist) # # self.widget.addWidget(self.hist, 0, 1) # self.hist.vb.setMouseEnabled(y=False) # makes user interaction a little easier # Create an array of histograms self.histograms = [] # Levels/color control with a histogram hist = HistogramLUTItem() hist.vb.setMouseEnabled( y=False) # makes user interaction a little easier hist.setImageItem(img) self.widget.addItem(hist) self.histograms.append(hist)
class QtPlotArea(QtControl, ProxyPlotArea): """ PyQtGraph Plot Widget """ __weakref__ = None widget = Typed(GraphicsLayoutWidget) def create_widget(self): self.widget = GraphicsLayoutWidget(self.parent_widget()) def init_layout(self): for child in self.children(): self.child_added(child) def child_added(self, child): # TODO support layouts if isinstance(child,AbstractQtPlotItem): d = child.declaration kwargs = dict(row=d.row,col=d.column) if d.row or d.column else {} self.widget.addItem(child.widget,**kwargs) def child_removed(self, child): if isinstance(child,AbstractQtPlotItem): self.widget.removeItem(child.widget)
class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.setupUserInterface() def setupUserInterface(self): frame = QtGui.QFrame() frameLayout = QtGui.QHBoxLayout() frame.setLayout(frameLayout) frame.setLineWidth(0) frame.setFrameStyle(QtGui.QFrame.Panel) frameLayout.setContentsMargins(0,0,5,0) self.viewMain = GraphicsLayoutWidget() self.viewMain.setMinimumSize(200,200) self.vb = MultiRoiViewBox(lockAspect=True,enableMenu=True) self.viewMain.addItem(self.vb) self.vb.disableAutoRange() self.setCentralWidget(self.viewMain)
class GraphicsWidget(QWidget): """Widget defined in Qt Designer""" def __init__(self, parent=None): # initialization of widget super(GraphicsWidget, self).__init__(parent) # Create a central Graphics Layout Widget self.widget = GraphicsLayoutWidget() # A plot area (ViewBox + axes) for displaying the image self.p1 = self.widget.addPlot() # Item for displaying image data self.img_item = ImageItem() self.img_item.axisOrder = 'row-major' self.p1.addItem(self.img_item) self.p1.getViewBox().invertY(True) # create a vertical box layout self.vbl = QVBoxLayout() # add widget to vertical box self.vbl.addWidget(self.widget) # set the layout to the vertical box self.setLayout(self.vbl) # Levels/color control with a histogram # self.hist = HistogramLUTWidget() # self.hist.setImageItem(self.img) # parent.horizontalLayout_View.addWidget(self.hist) # # self.widget.addWidget(self.hist, 0, 1) # self.hist.vb.setMouseEnabled(y=False) # makes user interaction a little easier # Create histogram # Levels/color control with a histogram self.histogram = HistogramLUTItem() # TODO Halve histogram width self.histogram.vb.setMouseEnabled( y=False) # makes user interaction a little easier self.histogram.setImageItem(self.img_item) self.widget.addItem(self.histogram)
def __init__(self): GraphicsLayoutWidget.__init__(self) uic.loadUi(parametersUIFile, self) self._tmpStars = None
def create_widget(self): self.widget = GraphicsLayoutWidget(self.parent_widget())
def setupUi(self, WidgetIsolate): WidgetIsolate.setObjectName("WidgetIsolate") WidgetIsolate.resize(351, 443) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( WidgetIsolate.sizePolicy().hasHeightForWidth()) WidgetIsolate.setSizePolicy(sizePolicy) WidgetIsolate.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.verticalLayout = QtWidgets.QVBoxLayout(WidgetIsolate) self.verticalLayout.setObjectName("verticalLayout") self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.labelSource = QtWidgets.QLabel(WidgetIsolate) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.labelSource.sizePolicy().hasHeightForWidth()) self.labelSource.setSizePolicy(sizePolicy) self.labelSource.setTextFormat(QtCore.Qt.PlainText) self.labelSource.setObjectName("labelSource") self.horizontalLayout_2.addWidget(self.labelSource) self.comboBoxSource = QtWidgets.QComboBox(WidgetIsolate) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.comboBoxSource.sizePolicy().hasHeightForWidth()) self.comboBoxSource.setSizePolicy(sizePolicy) self.comboBoxSource.setObjectName("comboBoxSource") self.horizontalLayout_2.addWidget(self.comboBoxSource) self.verticalLayout.addLayout(self.horizontalLayout_2) self.horizontalLayout_5 = QtWidgets.QHBoxLayout() self.horizontalLayout_5.setObjectName("horizontalLayout_5") self.labelROIs = QtWidgets.QLabel(WidgetIsolate) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.labelROIs.sizePolicy().hasHeightForWidth()) self.labelROIs.setSizePolicy(sizePolicy) self.labelROIs.setTextFormat(QtCore.Qt.PlainText) self.labelROIs.setObjectName("labelROIs") self.horizontalLayout_5.addWidget(self.labelROIs) self.comboBoxROIs = QtWidgets.QComboBox(WidgetIsolate) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.comboBoxROIs.sizePolicy().hasHeightForWidth()) self.comboBoxROIs.setSizePolicy(sizePolicy) self.comboBoxROIs.setObjectName("comboBoxROIs") self.comboBoxROIs.addItem("") self.horizontalLayout_5.addWidget(self.comboBoxROIs) self.verticalLayout.addLayout(self.horizontalLayout_5) self.tabWidgetRoiTypes = QtWidgets.QTabWidget(WidgetIsolate) self.tabWidgetRoiTypes.setEnabled(True) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.tabWidgetRoiTypes.sizePolicy().hasHeightForWidth()) self.tabWidgetRoiTypes.setSizePolicy(sizePolicy) self.tabWidgetRoiTypes.setMaximumSize(QtCore.QSize(350, 16777215)) self.tabWidgetRoiTypes.setTabBarAutoHide(False) self.tabWidgetRoiTypes.setObjectName("tabWidgetRoiTypes") self.tabCircle = QtWidgets.QWidget() self.tabCircle.setObjectName("tabCircle") self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.tabCircle) self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.formLayoutCenter = QtWidgets.QFormLayout() self.formLayoutCenter.setObjectName("formLayoutCenter") self.originXLabel = QtWidgets.QLabel(self.tabCircle) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.originXLabel.sizePolicy().hasHeightForWidth()) self.originXLabel.setSizePolicy(sizePolicy) self.originXLabel.setObjectName("originXLabel") self.formLayoutCenter.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.originXLabel) self.originXLineEdit = QtWidgets.QLineEdit(self.tabCircle) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.originXLineEdit.sizePolicy().hasHeightForWidth()) self.originXLineEdit.setSizePolicy(sizePolicy) self.originXLineEdit.setMinimumSize(QtCore.QSize(40, 0)) self.originXLineEdit.setObjectName("originXLineEdit") self.formLayoutCenter.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.originXLineEdit) self.originYLabel = QtWidgets.QLabel(self.tabCircle) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.originYLabel.sizePolicy().hasHeightForWidth()) self.originYLabel.setSizePolicy(sizePolicy) self.originYLabel.setObjectName("originYLabel") self.formLayoutCenter.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.originYLabel) self.originYLineEdit = QtWidgets.QLineEdit(self.tabCircle) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.originYLineEdit.sizePolicy().hasHeightForWidth()) self.originYLineEdit.setSizePolicy(sizePolicy) self.originYLineEdit.setMinimumSize(QtCore.QSize(40, 0)) self.originYLineEdit.setObjectName("originYLineEdit") self.formLayoutCenter.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.originYLineEdit) self.horizontalLayout_3.addLayout(self.formLayoutCenter) self.formLayoutRadius = QtWidgets.QFormLayout() self.formLayoutRadius.setObjectName("formLayoutRadius") self.radiusLabel = QtWidgets.QLabel(self.tabCircle) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.radiusLabel.sizePolicy().hasHeightForWidth()) self.radiusLabel.setSizePolicy(sizePolicy) self.radiusLabel.setObjectName("radiusLabel") self.formLayoutRadius.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.radiusLabel) self.radiusSpinBox = QtWidgets.QSpinBox(self.tabCircle) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.radiusSpinBox.sizePolicy().hasHeightForWidth()) self.radiusSpinBox.setSizePolicy(sizePolicy) self.radiusSpinBox.setMinimumSize(QtCore.QSize(50, 0)) self.radiusSpinBox.setMaximum(999) self.radiusSpinBox.setObjectName("radiusSpinBox") self.formLayoutRadius.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.radiusSpinBox) self.horizontalLayout_3.addLayout(self.formLayoutRadius) self.widgetPreview = GraphicsLayoutWidget(self.tabCircle) self.widgetPreview.setMinimumSize(QtCore.QSize(70, 70)) self.widgetPreview.setMaximumSize(QtCore.QSize(70, 70)) self.widgetPreview.setObjectName("widgetPreview") self.horizontalLayout_3.addWidget(self.widgetPreview) self.tabWidgetRoiTypes.addTab(self.tabCircle, "") self.tabPoly = QtWidgets.QWidget() self.tabPoly.setObjectName("tabPoly") self.tabWidgetRoiTypes.addTab(self.tabPoly, "") self.verticalLayout.addWidget(self.tabWidgetRoiTypes) self.widgetPreviewPlot = GraphicsLayoutWidget(WidgetIsolate) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.widgetPreviewPlot.sizePolicy().hasHeightForWidth()) self.widgetPreviewPlot.setSizePolicy(sizePolicy) self.widgetPreviewPlot.setMinimumSize(QtCore.QSize(70, 100)) self.widgetPreviewPlot.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.widgetPreviewPlot.setObjectName("widgetPreviewPlot") self.verticalLayout.addWidget(self.widgetPreviewPlot) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.checkBoxPreview = QtWidgets.QCheckBox(WidgetIsolate) font = QtGui.QFont() font.setBold(True) font.setItalic(False) font.setUnderline(False) font.setWeight(75) self.checkBoxPreview.setFont(font) self.checkBoxPreview.setObjectName("checkBoxPreview") self.horizontalLayout.addWidget(self.checkBoxPreview) spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.buttonBox = QtWidgets.QDialogButtonBox(WidgetIsolate) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.buttonBox.sizePolicy().hasHeightForWidth()) self.buttonBox.setSizePolicy(sizePolicy) self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setStandardButtons( QtWidgets.QDialogButtonBox.Apply | QtWidgets.QDialogButtonBox.Discard | QtWidgets.QDialogButtonBox.RestoreDefaults) self.buttonBox.setCenterButtons(False) self.buttonBox.setObjectName("buttonBox") self.horizontalLayout.addWidget(self.buttonBox) self.verticalLayout.addLayout(self.horizontalLayout) self.retranslateUi(WidgetIsolate) self.tabWidgetRoiTypes.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(WidgetIsolate)
class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(958, 727) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.gridLayout_2 = QtGui.QGridLayout(self.centralwidget) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.gridLayout_4 = QtGui.QGridLayout() self.gridLayout_4.setObjectName(_fromUtf8("gridLayout_4")) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.refreshname = QtGui.QPushButton(self.centralwidget) self.refreshname.setObjectName(_fromUtf8("refreshname")) self.horizontalLayout.addWidget(self.refreshname) self.playname = QtGui.QPushButton(self.centralwidget) self.playname.setObjectName(_fromUtf8("playname")) self.horizontalLayout.addWidget(self.playname) self.endname = QtGui.QPushButton(self.centralwidget) self.endname.setObjectName(_fromUtf8("endname")) self.horizontalLayout.addWidget(self.endname) self.gridLayout_4.addLayout(self.horizontalLayout, 5, 1, 1, 1) self.gridLayout_3 = QtGui.QGridLayout() self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3")) self.spinBoxyn4 = QtGui.QSpinBox(self.centralwidget) self.spinBoxyn4.setMinimum(-99) self.spinBoxyn4.setProperty("value", 3) self.spinBoxyn4.setObjectName(_fromUtf8("spinBoxyn4")) self.gridLayout_3.addWidget(self.spinBoxyn4, 3, 5, 1, 1) self.spinBoxyn3 = QtGui.QSpinBox(self.centralwidget) self.spinBoxyn3.setMinimum(-99) self.spinBoxyn3.setProperty("value", -1) self.spinBoxyn3.setObjectName(_fromUtf8("spinBoxyn3")) self.gridLayout_3.addWidget(self.spinBoxyn3, 3, 4, 1, 1) self.spinBoxyn2 = QtGui.QSpinBox(self.centralwidget) self.spinBoxyn2.setMinimum(-99) self.spinBoxyn2.setProperty("value", -1) self.spinBoxyn2.setObjectName(_fromUtf8("spinBoxyn2")) self.gridLayout_3.addWidget(self.spinBoxyn2, 3, 1, 1, 1) self.spinBoxnn1 = QtGui.QSpinBox(self.centralwidget) self.spinBoxnn1.setMinimum(-99) self.spinBoxnn1.setObjectName(_fromUtf8("spinBoxnn1")) self.gridLayout_3.addWidget(self.spinBoxnn1, 5, 2, 1, 1) self.spinBoxyn1 = QtGui.QSpinBox(self.centralwidget) self.spinBoxyn1.setMinimum(-99) self.spinBoxyn1.setProperty("value", 3) self.spinBoxyn1.setObjectName(_fromUtf8("spinBoxyn1")) self.gridLayout_3.addWidget(self.spinBoxyn1, 3, 0, 1, 1) self.spinBoxnn2 = QtGui.QSpinBox(self.centralwidget) self.spinBoxnn2.setMinimum(-99) self.spinBoxnn2.setObjectName(_fromUtf8("spinBoxnn2")) self.gridLayout_3.addWidget(self.spinBoxnn2, 5, 3, 1, 1) self.nnname = QtGui.QLabel(self.centralwidget) self.nnname.setObjectName(_fromUtf8("nnname")) self.gridLayout_3.addWidget(self.nnname, 4, 2, 1, 1) self.yn2name = QtGui.QLabel(self.centralwidget) self.yn2name.setObjectName(_fromUtf8("yn2name")) self.gridLayout_3.addWidget(self.yn2name, 2, 4, 1, 1) self.spinBoxyy2 = QtGui.QSpinBox(self.centralwidget) self.spinBoxyy2.setMinimum(-99) self.spinBoxyy2.setProperty("value", 2) self.spinBoxyy2.setObjectName(_fromUtf8("spinBoxyy2")) self.gridLayout_3.addWidget(self.spinBoxyy2, 1, 2, 1, 1) self.yn1name = QtGui.QLabel(self.centralwidget) self.yn1name.setObjectName(_fromUtf8("yn1name")) self.gridLayout_3.addWidget(self.yn1name, 2, 0, 1, 1) self.spinBoxyy1 = QtGui.QSpinBox(self.centralwidget) self.spinBoxyy1.setMinimum(-99) self.spinBoxyy1.setProperty("value", 2) self.spinBoxyy1.setObjectName(_fromUtf8("spinBoxyy1")) self.gridLayout_3.addWidget(self.spinBoxyy1, 1, 3, 1, 1) self.yyname = QtGui.QLabel(self.centralwidget) self.yyname.setObjectName(_fromUtf8("yyname")) self.gridLayout_3.addWidget(self.yyname, 0, 2, 1, 1) self.label = QtGui.QLabel(self.centralwidget) self.label.setObjectName(_fromUtf8("label")) self.gridLayout_3.addWidget(self.label, 0, 3, 1, 1) self.label_2 = QtGui.QLabel(self.centralwidget) self.label_2.setObjectName(_fromUtf8("label_2")) self.gridLayout_3.addWidget(self.label_2, 2, 1, 1, 1) self.label_3 = QtGui.QLabel(self.centralwidget) self.label_3.setObjectName(_fromUtf8("label_3")) self.gridLayout_3.addWidget(self.label_3, 2, 5, 1, 1) self.label_4 = QtGui.QLabel(self.centralwidget) self.label_4.setObjectName(_fromUtf8("label_4")) self.gridLayout_3.addWidget(self.label_4, 4, 3, 1, 1) self.gridLayout_4.addLayout(self.gridLayout_3, 4, 1, 1, 1) self.gridLayout = QtGui.QGridLayout() self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.spinBox = QtGui.QSpinBox(self.centralwidget) self.spinBox.setProperty("value", 20) self.spinBox.setObjectName(_fromUtf8("spinBox")) self.gridLayout.addWidget(self.spinBox, 4, 2, 1, 1) self.randomname = QtGui.QLabel(self.centralwidget) self.randomname.setAlignment(QtCore.Qt.AlignCenter) self.randomname.setObjectName(_fromUtf8("randomname")) self.gridLayout.addWidget(self.randomname, 4, 0, 1, 1) self.spinBoxno = QtGui.QSpinBox(self.centralwidget) self.spinBoxno.setProperty("value", 20) self.spinBoxno.setObjectName(_fromUtf8("spinBoxno")) self.gridLayout.addWidget(self.spinBoxno, 1, 2, 1, 1) self.yesnoname = QtGui.QLabel(self.centralwidget) self.yesnoname.setAlignment(QtCore.Qt.AlignCenter) self.yesnoname.setObjectName(_fromUtf8("yesnoname")) self.gridLayout.addWidget(self.yesnoname, 2, 0, 1, 1) self.yesname = QtGui.QLabel(self.centralwidget) self.yesname.setAlignment(QtCore.Qt.AlignCenter) self.yesname.setObjectName(_fromUtf8("yesname")) self.gridLayout.addWidget(self.yesname, 0, 0, 1, 1) self.horizontalSlider = QtGui.QSlider(self.centralwidget) self.horizontalSlider.setProperty("value", 20) self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal) self.horizontalSlider.setObjectName(_fromUtf8("horizontalSlider")) self.gridLayout.addWidget(self.horizontalSlider, 0, 1, 1, 1) self.horizontalSlider_2 = QtGui.QSlider(self.centralwidget) self.horizontalSlider_2.setProperty("value", 20) self.horizontalSlider_2.setOrientation(QtCore.Qt.Horizontal) self.horizontalSlider_2.setObjectName(_fromUtf8("horizontalSlider_2")) self.gridLayout.addWidget(self.horizontalSlider_2, 1, 1, 1, 1) self.horizontalSlider_3 = QtGui.QSlider(self.centralwidget) self.horizontalSlider_3.setProperty("value", 20) self.horizontalSlider_3.setOrientation(QtCore.Qt.Horizontal) self.horizontalSlider_3.setObjectName(_fromUtf8("horizontalSlider_3")) self.gridLayout.addWidget(self.horizontalSlider_3, 2, 1, 1, 1) self.spinBoxyesno = QtGui.QSpinBox(self.centralwidget) self.spinBoxyesno.setProperty("value", 20) self.spinBoxyesno.setObjectName(_fromUtf8("spinBoxyesno")) self.gridLayout.addWidget(self.spinBoxyesno, 2, 2, 1, 1) self.spinBoxyes = QtGui.QSpinBox(self.centralwidget) self.spinBoxyes.setProperty("value", 20) self.spinBoxyes.setObjectName(_fromUtf8("spinBoxyes")) self.gridLayout.addWidget(self.spinBoxyes, 0, 2, 1, 1) self.spinBoxlike = QtGui.QSpinBox(self.centralwidget) self.spinBoxlike.setProperty("value", 20) self.spinBoxlike.setObjectName(_fromUtf8("spinBoxlike")) self.gridLayout.addWidget(self.spinBoxlike, 3, 2, 1, 1) self.noname = QtGui.QLabel(self.centralwidget) self.noname.setAlignment(QtCore.Qt.AlignCenter) self.noname.setObjectName(_fromUtf8("noname")) self.gridLayout.addWidget(self.noname, 1, 0, 1, 1) self.likename = QtGui.QLabel(self.centralwidget) self.likename.setAlignment(QtCore.Qt.AlignCenter) self.likename.setObjectName(_fromUtf8("likename")) self.gridLayout.addWidget(self.likename, 3, 0, 1, 1) self.horizontalSlider_4 = QtGui.QSlider(self.centralwidget) self.horizontalSlider_4.setProperty("value", 20) self.horizontalSlider_4.setOrientation(QtCore.Qt.Horizontal) self.horizontalSlider_4.setObjectName(_fromUtf8("horizontalSlider_4")) self.gridLayout.addWidget(self.horizontalSlider_4, 3, 1, 1, 1) self.horizontalSlider_5 = QtGui.QSlider(self.centralwidget) self.horizontalSlider_5.setProperty("value", 20) self.horizontalSlider_5.setOrientation(QtCore.Qt.Horizontal) self.horizontalSlider_5.setObjectName(_fromUtf8("horizontalSlider_5")) self.gridLayout.addWidget(self.horizontalSlider_5, 4, 1, 1, 1) self.gridLayout_4.addLayout(self.gridLayout, 1, 1, 1, 1) self.gridLayout_5 = QtGui.QGridLayout() self.gridLayout_5.setObjectName(_fromUtf8("gridLayout_5")) self.spinBoxlose = QtGui.QSpinBox(self.centralwidget) self.spinBoxlose.setProperty("value", 5) self.spinBoxlose.setObjectName(_fromUtf8("spinBoxlose")) self.gridLayout_5.addWidget(self.spinBoxlose, 1, 2, 1, 1) self.losename = QtGui.QLabel(self.centralwidget) self.losename.setObjectName(_fromUtf8("losename")) self.gridLayout_5.addWidget(self.losename, 1, 3, 1, 1) self.spinBoxwin = QtGui.QSpinBox(self.centralwidget) self.spinBoxwin.setProperty("value", 5) self.spinBoxwin.setObjectName(_fromUtf8("spinBoxwin")) self.gridLayout_5.addWidget(self.spinBoxwin, 1, 0, 1, 1) self.winname = QtGui.QLabel(self.centralwidget) self.winname.setObjectName(_fromUtf8("winname")) self.gridLayout_5.addWidget(self.winname, 1, 1, 1, 1) self.spinBoxround = QtGui.QSpinBox(self.centralwidget) self.spinBoxround.setProperty("value", 5) self.spinBoxround.setObjectName(_fromUtf8("spinBoxround")) self.gridLayout_5.addWidget(self.spinBoxround, 0, 0, 1, 1) self.roundname = QtGui.QLabel(self.centralwidget) self.roundname.setObjectName(_fromUtf8("roundname")) self.gridLayout_5.addWidget(self.roundname, 0, 1, 1, 1) self.mistakename = QtGui.QLabel(self.centralwidget) self.mistakename.setObjectName(_fromUtf8("mistakename")) self.gridLayout_5.addWidget(self.mistakename, 2, 0, 1, 1) self.spinBoxmistake = QtGui.QSpinBox(self.centralwidget) self.spinBoxmistake.setObjectName(_fromUtf8("spinBoxmistake")) self.gridLayout_5.addWidget(self.spinBoxmistake, 2, 1, 1, 1) self.label_5 = QtGui.QLabel(self.centralwidget) self.label_5.setObjectName(_fromUtf8("label_5")) self.gridLayout_5.addWidget(self.label_5, 2, 2, 1, 1) self.gridLayout_4.addLayout(self.gridLayout_5, 5, 0, 1, 1) self.picturename = GraphicsLayoutWidget(self.centralwidget) self.picturename.setObjectName(_fromUtf8("picturename")) self.gridLayout_4.addWidget(self.picturename, 0, 0, 3, 1) spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.gridLayout_4.addItem(spacerItem, 2, 1, 1, 1) spacerItem1 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.gridLayout_4.addItem(spacerItem1, 0, 1, 1, 1) self.textEdit = QtGui.QTextEdit(self.centralwidget) self.textEdit.setObjectName(_fromUtf8("textEdit")) self.gridLayout_4.addWidget(self.textEdit, 4, 0, 1, 1) self.gridLayout_2.addLayout(self.gridLayout_4, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 958, 21)) self.menubar.setObjectName(_fromUtf8("menubar")) MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) MainWindow.setStatusBar(self.statusbar) self.endname.clicked.connect(self.ending) ###추가한부분 self.refreshname.clicked.connect(self.refreshing) self.playname.clicked.connect(self.playing) self.retranslateUi(MainWindow) QtCore.QObject.connect(self.horizontalSlider, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxyes.setValue) QtCore.QObject.connect(self.horizontalSlider_2, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxno.setValue) QtCore.QObject.connect(self.horizontalSlider_3, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxyesno.setValue) QtCore.QObject.connect(self.horizontalSlider_4, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxlike.setValue) QtCore.QObject.connect(self.spinBoxyy1, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxyy2.setValue) QtCore.QObject.connect(self.spinBoxyn2, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxyn3.setValue) QtCore.QObject.connect(self.spinBoxyn1, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxyn4.setValue) QtCore.QObject.connect(self.spinBoxnn1, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxnn2.setValue) QtCore.QObject.connect(self.spinBoxwin, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxlose.setValue) QtCore.QObject.connect(self.horizontalSlider_5, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBox.setValue) QtCore.QObject.connect(self.spinBoxyy2, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxyy1.setValue) QtCore.QObject.connect(self.spinBoxyn3, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxyn2.setValue) QtCore.QObject.connect(self.spinBoxyn4, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxyn1.setValue) QtCore.QObject.connect(self.spinBoxnn2, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxnn1.setValue) QtCore.QObject.connect(self.spinBoxlose, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxwin.setValue) QtCore.QObject.connect(self.spinBoxyes, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.horizontalSlider.setValue) QtCore.QObject.connect(self.spinBoxno, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.horizontalSlider_2.setValue) QtCore.QObject.connect(self.spinBoxyesno, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.horizontalSlider_3.setValue) QtCore.QObject.connect(self.spinBoxlike, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.horizontalSlider_4.setValue) QtCore.QObject.connect(self.spinBox, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.horizontalSlider_5.setValue) QtCore.QMetaObject.connectSlotsByName(MainWindow) def ending(self): ###추가한부분 sys.exit() def playing(self): class Player(object): def __init__(self): self.score = 0 def algorithm(self): raise NotImplementedError ###하위 클래스에서 구현이 안되어있을 경우 에러 발생 class OnlyHelper(Player): def __init__(self): Player.__init__(self) def algorithm(self): return True class OnlyBetrayer(Player): def __init__(self): Player.__init__(self) def algorithm(self): return False class ReactPlayer(Player): ### 상대의 행동에 영향받는 플레이어의 클래스 def __init__(self): Player.__init__(self) self.prevEnemyAction = True def update(self, input): raise NotImplementedError class Mirror(ReactPlayer): def __init__(self): ReactPlayer.__init__(self) def update(self, input): self.prevEnemyAction = input ### 상대의 전번선택을 input 변수로 받아와서 prevEnemyAction에 저장 def algorithm(self): return self.prevEnemyAction ### prevEnemyAction을 따라서 행동함 class Revenger(ReactPlayer): def __init__(self): ReactPlayer.__init__(self) def update(self, input): self.prevEnemyAction &= input ### A &= B : only when A and B is True, A is True def algorithm(self): return self.prevEnemyAction class Randomer(Player): def __init__(self): Player.__init__(self) def algorithm(self): return bool(random.randint( 0, 1)) ### bool타입 활용 (bool(1) = True, bool(0)= False)) class Game(object): def __init__(self, PlayerTypes, Option): self.Playerlist = [] self.option = Option self.PlayerClass = [ OnlyHelper, OnlyBetrayer, Mirror, Revenger, Randomer ] for i in range(0, 5): for j in range(0, PlayerTypes[i]): self.Playerlist.append(self.PlayerClass[i]()) lineUp = [] for i in range(0, self.Playerlist.__len__()): for j in range(i + 1, self.Playerlist.__len__()): lineUp.append((i, j)) self.g = Graph(lineUp) class Option(object): def __init__(self, reward, rounds, leagueLoop): self.rounds = rounds self.reward = reward self.leagueLoop = leagueLoop @staticmethod # 호출된 클래스나 인스턴스에 대해 모르는 메소드 def validate(A, B): params = [A, B] res = list(map(lambda x: x.algorithm(), params)) for i in range(0, 2): if type(params[i]) is ReactPlayer: params[i].update(res[(i + 1) % 2]) if res[0] and res[1]: # 둘 다 협력 return 0 elif not (res[0] or res[1]): # 둘 다 배신 return 1 elif res[1]: # A 가 배신 return 2 else: # B 가 배신 return 3 def Battle(self, A, B): result = Game.validate(A, B) if result == 0: A.score += self.option.reward['BothHelp'] B.score += self.option.reward['BothHelp'] elif result == 1: A.score += self.option.reward['BothBetray'] B.score += self.option.reward['BothBetray'] elif result == 2: A.score += self.option.reward['BetrayBenefit'] B.score += self.option.reward['HelpPenalty'] else: A.score += self.option.reward['HelpPenalty'] B.score += self.option.reward['BetrayBenefit'] def mutation(self): print("----------------------") self.Playerlist.sort(key=lambda x: x.score, reverse=True) for i in range(0, 5): self.Playerlist.pop() for i in range(0, 5): self.Playerlist.append(type(self.Playerlist[i])()) def monitor(self): winnerList = [] winnerCount = [] #for i in self.Playerlist: #print(i.score, type(i).__name__) for i in range(0, len(self.Playerlist)): winnerList.append(str(type(self.Playerlist[i]))) for i in self.PlayerClass: winnerCount.append(winnerList.count(str(i))) return 'Remain number\n\nHELPman:{} \nREJECTman:{} \nimitator:{} \nrevenger:{} \nrandom:{}'.format( winnerCount[0], winnerCount[1], winnerCount[2], winnerCount[3], winnerCount[4]) def scoreResetter(self): for i in self.Playerlist: i.score = 0 def league(self): playerlength = self.Playerlist.__len__() for i in range(0, playerlength): for j in range(i + 1, playerlength): for k in range(0, self.option.rounds): self.Battle(self.Playerlist[i], self.Playerlist[j]) if (type(self.Playerlist[i]) is ReactPlayer): self.Playerlist[i].update(True) if (type(self.Playerlist[j]) is ReactPlayer): self.Playerlist[j].update(True) self.mutation() self.scoreResetter() def leagueStart(self): for i in range(0, self.option.leagueLoop): self.league() self.visualize() def graphSetter(self): self.g.vs["player"] = list( map(lambda x: type(x).__name__, self.Playerlist)) def visualize(self): gameInstance.graphSetter() myGraph = self.g layout = myGraph.layout_circle() ## dim=2 color_dict = { "Mirror": "green", "Randomer": "pink", "Revenger": "yellow", "OnlyBetrayer": "red", "OnlyHelper": "blue" } graphic = plot(myGraph, layout=layout, bbox=(512, 512), margin=16, vertex_color=[ color_dict[player] for player in myGraph.vs["player"] ], vertex_size=16) gameInstance = Game(PlayerTypes=[ self.spinBoxyes.value(), self.spinBoxno.value(), self.spinBoxyesno.value(), self.spinBoxlike.value(), self.spinBox.value() ], Option=Game.Option( reward={ 'BothBetray': self.spinBoxnn1.value(), 'BothHelp': self.spinBoxyy1.value(), 'BetrayBenefit': self.spinBoxyn1.value(), 'HelpPenalty': self.spinBoxyn2.value() }, rounds=1, leagueLoop=self.spinBoxround.value())) gameInstance.leagueStart() # 시작 버튼을 누르면 실행 self.textEdit.setText(str(gameInstance.monitor())) # 결과를 보고 싶습니다 def refreshing(self): self.spinBoxyy1.setProperty("value", 2) self.spinBoxyy2.setProperty("value", 2) self.spinBoxyn1.setProperty("value", 3) self.spinBoxyn2.setProperty("value", -1) self.spinBoxyn3.setProperty("value", -1) self.spinBoxyn4.setProperty("value", 3) self.horizontalSlider_2.setProperty("value", 20) self.spinBoxno.setProperty("value", 20) self.horizontalSlider.setProperty("value", 20) self.horizontalSlider_3.setProperty("value", 20) self.spinBoxyesno.setProperty("value", 20) self.spinBoxyes.setProperty("value", 20) self.horizontalSlider_4.setProperty("value", 20) self.spinBoxlike.setProperty("value", 20) self.spinBoxround.setProperty("value", 5) self.spinBoxlose.setProperty("value", 5) self.spinBoxwin.setProperty("value", 5) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None)) self.refreshname.setText( _translate("MainWindow", "initialization", None)) self.playname.setText(_translate("MainWindow", "play", None)) self.endname.setText(_translate("MainWindow", "end", None)) self.nnname.setText(_translate("MainWindow", "reject", None)) self.yn2name.setText(_translate("MainWindow", "help", None)) self.yn1name.setText(_translate("MainWindow", "reject", None)) self.yyname.setText(_translate("MainWindow", "help", None)) self.label.setText(_translate("MainWindow", "help", None)) self.label_2.setText(_translate("MainWindow", "help", None)) self.label_3.setText(_translate("MainWindow", "reject", None)) self.label_4.setText(_translate("MainWindow", "reject", None)) self.randomname.setText(_translate("MainWindow", "random", None)) self.yesnoname.setText(_translate("MainWindow", " imitator", None)) self.yesname.setText(_translate("MainWindow", "HELPman", None)) self.noname.setText(_translate("MainWindow", "REJECTman", None)) self.likename.setText(_translate("MainWindow", "revenger", None)) self.losename.setText(_translate("MainWindow", "lose", None)) self.winname.setText(_translate("MainWindow", "win", None)) self.roundname.setText(_translate("MainWindow", "round", None)) self.mistakename.setText(_translate("MainWindow", "mistake", None)) self.label_5.setText(_translate("MainWindow", "%", None))
def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(958, 727) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.gridLayout_2 = QtGui.QGridLayout(self.centralwidget) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.gridLayout_4 = QtGui.QGridLayout() self.gridLayout_4.setObjectName(_fromUtf8("gridLayout_4")) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.refreshname = QtGui.QPushButton(self.centralwidget) self.refreshname.setObjectName(_fromUtf8("refreshname")) self.horizontalLayout.addWidget(self.refreshname) self.playname = QtGui.QPushButton(self.centralwidget) self.playname.setObjectName(_fromUtf8("playname")) self.horizontalLayout.addWidget(self.playname) self.endname = QtGui.QPushButton(self.centralwidget) self.endname.setObjectName(_fromUtf8("endname")) self.horizontalLayout.addWidget(self.endname) self.gridLayout_4.addLayout(self.horizontalLayout, 5, 1, 1, 1) self.gridLayout_3 = QtGui.QGridLayout() self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3")) self.spinBoxyn4 = QtGui.QSpinBox(self.centralwidget) self.spinBoxyn4.setMinimum(-99) self.spinBoxyn4.setProperty("value", 3) self.spinBoxyn4.setObjectName(_fromUtf8("spinBoxyn4")) self.gridLayout_3.addWidget(self.spinBoxyn4, 3, 5, 1, 1) self.spinBoxyn3 = QtGui.QSpinBox(self.centralwidget) self.spinBoxyn3.setMinimum(-99) self.spinBoxyn3.setProperty("value", -1) self.spinBoxyn3.setObjectName(_fromUtf8("spinBoxyn3")) self.gridLayout_3.addWidget(self.spinBoxyn3, 3, 4, 1, 1) self.spinBoxyn2 = QtGui.QSpinBox(self.centralwidget) self.spinBoxyn2.setMinimum(-99) self.spinBoxyn2.setProperty("value", -1) self.spinBoxyn2.setObjectName(_fromUtf8("spinBoxyn2")) self.gridLayout_3.addWidget(self.spinBoxyn2, 3, 1, 1, 1) self.spinBoxnn1 = QtGui.QSpinBox(self.centralwidget) self.spinBoxnn1.setMinimum(-99) self.spinBoxnn1.setObjectName(_fromUtf8("spinBoxnn1")) self.gridLayout_3.addWidget(self.spinBoxnn1, 5, 2, 1, 1) self.spinBoxyn1 = QtGui.QSpinBox(self.centralwidget) self.spinBoxyn1.setMinimum(-99) self.spinBoxyn1.setProperty("value", 3) self.spinBoxyn1.setObjectName(_fromUtf8("spinBoxyn1")) self.gridLayout_3.addWidget(self.spinBoxyn1, 3, 0, 1, 1) self.spinBoxnn2 = QtGui.QSpinBox(self.centralwidget) self.spinBoxnn2.setMinimum(-99) self.spinBoxnn2.setObjectName(_fromUtf8("spinBoxnn2")) self.gridLayout_3.addWidget(self.spinBoxnn2, 5, 3, 1, 1) self.nnname = QtGui.QLabel(self.centralwidget) self.nnname.setObjectName(_fromUtf8("nnname")) self.gridLayout_3.addWidget(self.nnname, 4, 2, 1, 1) self.yn2name = QtGui.QLabel(self.centralwidget) self.yn2name.setObjectName(_fromUtf8("yn2name")) self.gridLayout_3.addWidget(self.yn2name, 2, 4, 1, 1) self.spinBoxyy2 = QtGui.QSpinBox(self.centralwidget) self.spinBoxyy2.setMinimum(-99) self.spinBoxyy2.setProperty("value", 2) self.spinBoxyy2.setObjectName(_fromUtf8("spinBoxyy2")) self.gridLayout_3.addWidget(self.spinBoxyy2, 1, 2, 1, 1) self.yn1name = QtGui.QLabel(self.centralwidget) self.yn1name.setObjectName(_fromUtf8("yn1name")) self.gridLayout_3.addWidget(self.yn1name, 2, 0, 1, 1) self.spinBoxyy1 = QtGui.QSpinBox(self.centralwidget) self.spinBoxyy1.setMinimum(-99) self.spinBoxyy1.setProperty("value", 2) self.spinBoxyy1.setObjectName(_fromUtf8("spinBoxyy1")) self.gridLayout_3.addWidget(self.spinBoxyy1, 1, 3, 1, 1) self.yyname = QtGui.QLabel(self.centralwidget) self.yyname.setObjectName(_fromUtf8("yyname")) self.gridLayout_3.addWidget(self.yyname, 0, 2, 1, 1) self.label = QtGui.QLabel(self.centralwidget) self.label.setObjectName(_fromUtf8("label")) self.gridLayout_3.addWidget(self.label, 0, 3, 1, 1) self.label_2 = QtGui.QLabel(self.centralwidget) self.label_2.setObjectName(_fromUtf8("label_2")) self.gridLayout_3.addWidget(self.label_2, 2, 1, 1, 1) self.label_3 = QtGui.QLabel(self.centralwidget) self.label_3.setObjectName(_fromUtf8("label_3")) self.gridLayout_3.addWidget(self.label_3, 2, 5, 1, 1) self.label_4 = QtGui.QLabel(self.centralwidget) self.label_4.setObjectName(_fromUtf8("label_4")) self.gridLayout_3.addWidget(self.label_4, 4, 3, 1, 1) self.gridLayout_4.addLayout(self.gridLayout_3, 4, 1, 1, 1) self.gridLayout = QtGui.QGridLayout() self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.spinBox = QtGui.QSpinBox(self.centralwidget) self.spinBox.setProperty("value", 20) self.spinBox.setObjectName(_fromUtf8("spinBox")) self.gridLayout.addWidget(self.spinBox, 4, 2, 1, 1) self.randomname = QtGui.QLabel(self.centralwidget) self.randomname.setAlignment(QtCore.Qt.AlignCenter) self.randomname.setObjectName(_fromUtf8("randomname")) self.gridLayout.addWidget(self.randomname, 4, 0, 1, 1) self.spinBoxno = QtGui.QSpinBox(self.centralwidget) self.spinBoxno.setProperty("value", 20) self.spinBoxno.setObjectName(_fromUtf8("spinBoxno")) self.gridLayout.addWidget(self.spinBoxno, 1, 2, 1, 1) self.yesnoname = QtGui.QLabel(self.centralwidget) self.yesnoname.setAlignment(QtCore.Qt.AlignCenter) self.yesnoname.setObjectName(_fromUtf8("yesnoname")) self.gridLayout.addWidget(self.yesnoname, 2, 0, 1, 1) self.yesname = QtGui.QLabel(self.centralwidget) self.yesname.setAlignment(QtCore.Qt.AlignCenter) self.yesname.setObjectName(_fromUtf8("yesname")) self.gridLayout.addWidget(self.yesname, 0, 0, 1, 1) self.horizontalSlider = QtGui.QSlider(self.centralwidget) self.horizontalSlider.setProperty("value", 20) self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal) self.horizontalSlider.setObjectName(_fromUtf8("horizontalSlider")) self.gridLayout.addWidget(self.horizontalSlider, 0, 1, 1, 1) self.horizontalSlider_2 = QtGui.QSlider(self.centralwidget) self.horizontalSlider_2.setProperty("value", 20) self.horizontalSlider_2.setOrientation(QtCore.Qt.Horizontal) self.horizontalSlider_2.setObjectName(_fromUtf8("horizontalSlider_2")) self.gridLayout.addWidget(self.horizontalSlider_2, 1, 1, 1, 1) self.horizontalSlider_3 = QtGui.QSlider(self.centralwidget) self.horizontalSlider_3.setProperty("value", 20) self.horizontalSlider_3.setOrientation(QtCore.Qt.Horizontal) self.horizontalSlider_3.setObjectName(_fromUtf8("horizontalSlider_3")) self.gridLayout.addWidget(self.horizontalSlider_3, 2, 1, 1, 1) self.spinBoxyesno = QtGui.QSpinBox(self.centralwidget) self.spinBoxyesno.setProperty("value", 20) self.spinBoxyesno.setObjectName(_fromUtf8("spinBoxyesno")) self.gridLayout.addWidget(self.spinBoxyesno, 2, 2, 1, 1) self.spinBoxyes = QtGui.QSpinBox(self.centralwidget) self.spinBoxyes.setProperty("value", 20) self.spinBoxyes.setObjectName(_fromUtf8("spinBoxyes")) self.gridLayout.addWidget(self.spinBoxyes, 0, 2, 1, 1) self.spinBoxlike = QtGui.QSpinBox(self.centralwidget) self.spinBoxlike.setProperty("value", 20) self.spinBoxlike.setObjectName(_fromUtf8("spinBoxlike")) self.gridLayout.addWidget(self.spinBoxlike, 3, 2, 1, 1) self.noname = QtGui.QLabel(self.centralwidget) self.noname.setAlignment(QtCore.Qt.AlignCenter) self.noname.setObjectName(_fromUtf8("noname")) self.gridLayout.addWidget(self.noname, 1, 0, 1, 1) self.likename = QtGui.QLabel(self.centralwidget) self.likename.setAlignment(QtCore.Qt.AlignCenter) self.likename.setObjectName(_fromUtf8("likename")) self.gridLayout.addWidget(self.likename, 3, 0, 1, 1) self.horizontalSlider_4 = QtGui.QSlider(self.centralwidget) self.horizontalSlider_4.setProperty("value", 20) self.horizontalSlider_4.setOrientation(QtCore.Qt.Horizontal) self.horizontalSlider_4.setObjectName(_fromUtf8("horizontalSlider_4")) self.gridLayout.addWidget(self.horizontalSlider_4, 3, 1, 1, 1) self.horizontalSlider_5 = QtGui.QSlider(self.centralwidget) self.horizontalSlider_5.setProperty("value", 20) self.horizontalSlider_5.setOrientation(QtCore.Qt.Horizontal) self.horizontalSlider_5.setObjectName(_fromUtf8("horizontalSlider_5")) self.gridLayout.addWidget(self.horizontalSlider_5, 4, 1, 1, 1) self.gridLayout_4.addLayout(self.gridLayout, 1, 1, 1, 1) self.gridLayout_5 = QtGui.QGridLayout() self.gridLayout_5.setObjectName(_fromUtf8("gridLayout_5")) self.spinBoxlose = QtGui.QSpinBox(self.centralwidget) self.spinBoxlose.setProperty("value", 5) self.spinBoxlose.setObjectName(_fromUtf8("spinBoxlose")) self.gridLayout_5.addWidget(self.spinBoxlose, 1, 2, 1, 1) self.losename = QtGui.QLabel(self.centralwidget) self.losename.setObjectName(_fromUtf8("losename")) self.gridLayout_5.addWidget(self.losename, 1, 3, 1, 1) self.spinBoxwin = QtGui.QSpinBox(self.centralwidget) self.spinBoxwin.setProperty("value", 5) self.spinBoxwin.setObjectName(_fromUtf8("spinBoxwin")) self.gridLayout_5.addWidget(self.spinBoxwin, 1, 0, 1, 1) self.winname = QtGui.QLabel(self.centralwidget) self.winname.setObjectName(_fromUtf8("winname")) self.gridLayout_5.addWidget(self.winname, 1, 1, 1, 1) self.spinBoxround = QtGui.QSpinBox(self.centralwidget) self.spinBoxround.setProperty("value", 5) self.spinBoxround.setObjectName(_fromUtf8("spinBoxround")) self.gridLayout_5.addWidget(self.spinBoxround, 0, 0, 1, 1) self.roundname = QtGui.QLabel(self.centralwidget) self.roundname.setObjectName(_fromUtf8("roundname")) self.gridLayout_5.addWidget(self.roundname, 0, 1, 1, 1) self.mistakename = QtGui.QLabel(self.centralwidget) self.mistakename.setObjectName(_fromUtf8("mistakename")) self.gridLayout_5.addWidget(self.mistakename, 2, 0, 1, 1) self.spinBoxmistake = QtGui.QSpinBox(self.centralwidget) self.spinBoxmistake.setObjectName(_fromUtf8("spinBoxmistake")) self.gridLayout_5.addWidget(self.spinBoxmistake, 2, 1, 1, 1) self.label_5 = QtGui.QLabel(self.centralwidget) self.label_5.setObjectName(_fromUtf8("label_5")) self.gridLayout_5.addWidget(self.label_5, 2, 2, 1, 1) self.gridLayout_4.addLayout(self.gridLayout_5, 5, 0, 1, 1) self.picturename = GraphicsLayoutWidget(self.centralwidget) self.picturename.setObjectName(_fromUtf8("picturename")) self.gridLayout_4.addWidget(self.picturename, 0, 0, 3, 1) spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.gridLayout_4.addItem(spacerItem, 2, 1, 1, 1) spacerItem1 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.gridLayout_4.addItem(spacerItem1, 0, 1, 1, 1) self.textEdit = QtGui.QTextEdit(self.centralwidget) self.textEdit.setObjectName(_fromUtf8("textEdit")) self.gridLayout_4.addWidget(self.textEdit, 4, 0, 1, 1) self.gridLayout_2.addLayout(self.gridLayout_4, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 958, 21)) self.menubar.setObjectName(_fromUtf8("menubar")) MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) MainWindow.setStatusBar(self.statusbar) self.endname.clicked.connect(self.ending) ###추가한부분 self.refreshname.clicked.connect(self.refreshing) self.playname.clicked.connect(self.playing) self.retranslateUi(MainWindow) QtCore.QObject.connect(self.horizontalSlider, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxyes.setValue) QtCore.QObject.connect(self.horizontalSlider_2, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxno.setValue) QtCore.QObject.connect(self.horizontalSlider_3, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxyesno.setValue) QtCore.QObject.connect(self.horizontalSlider_4, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxlike.setValue) QtCore.QObject.connect(self.spinBoxyy1, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxyy2.setValue) QtCore.QObject.connect(self.spinBoxyn2, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxyn3.setValue) QtCore.QObject.connect(self.spinBoxyn1, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxyn4.setValue) QtCore.QObject.connect(self.spinBoxnn1, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxnn2.setValue) QtCore.QObject.connect(self.spinBoxwin, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxlose.setValue) QtCore.QObject.connect(self.horizontalSlider_5, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBox.setValue) QtCore.QObject.connect(self.spinBoxyy2, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxyy1.setValue) QtCore.QObject.connect(self.spinBoxyn3, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxyn2.setValue) QtCore.QObject.connect(self.spinBoxyn4, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxyn1.setValue) QtCore.QObject.connect(self.spinBoxnn2, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxnn1.setValue) QtCore.QObject.connect(self.spinBoxlose, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.spinBoxwin.setValue) QtCore.QObject.connect(self.spinBoxyes, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.horizontalSlider.setValue) QtCore.QObject.connect(self.spinBoxno, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.horizontalSlider_2.setValue) QtCore.QObject.connect(self.spinBoxyesno, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.horizontalSlider_3.setValue) QtCore.QObject.connect(self.spinBoxlike, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.horizontalSlider_4.setValue) QtCore.QObject.connect(self.spinBox, QtCore.SIGNAL(_fromUtf8("valueChanged(int)")), self.horizontalSlider_5.setValue) QtCore.QMetaObject.connectSlotsByName(MainWindow)
class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.loadIcons() self.setupUserInterface() self.setupSignals() self.__version__ = __version__ # Initialise variables self.imageFiles = {} self.timeData = None self.plotWin = None self.imageWin = None self.BMDchange = None self.roiNames = None def loadIcons(self): """ Load icons """ self.icons = dict([ ('BMDanalyseIcon', QtGui.QIcon(os.path.join(absDirPath,"icons","logo.png"))), ('imageAddIcon', QtGui.QIcon(os.path.join(absDirPath,"icons","file_add.png"))), ('imageRemIcon', QtGui.QIcon(os.path.join(absDirPath,"icons","file_delete2.png"))), ('imageDownIcon', QtGui.QIcon(os.path.join(absDirPath,"icons","arrow-up-2.png"))), ('imageUpIcon', QtGui.QIcon(os.path.join(absDirPath,"icons","arrow-down-2.png"))), ('imagePrevIcon', QtGui.QIcon(os.path.join(absDirPath,"icons","arrow-left.png"))), ('imageNextIcon', QtGui.QIcon(os.path.join(absDirPath,"icons","arrow-right.png"))), ('roiAddIcon', QtGui.QIcon(os.path.join(absDirPath,"icons","green-add3.png"))), ('roiRectIcon', QtGui.QIcon(os.path.join(absDirPath,"icons","rectangularIcon.png"))), ('roiPolyIcon', QtGui.QIcon(os.path.join(absDirPath,"icons","polygonIcon.png"))), ('roiRemIcon', QtGui.QIcon(os.path.join(absDirPath,"icons","red_delete.png"))), ('roiSaveIcon', QtGui.QIcon(os.path.join(absDirPath,"icons","filesave.png"))), ('roiCopyIcon', QtGui.QIcon(os.path.join(absDirPath,"icons","file_copy.png"))), ('roiLoadIcon', QtGui.QIcon(os.path.join(absDirPath,"icons","opened-folder.png")))]) def setupUserInterface(self): """ Initialise the User Interface """ # Left frame leftFrame = QtGui.QFrame() leftFrameLayout = QtGui.QHBoxLayout() leftFrame.setLayout(leftFrameLayout) leftFrame.setLineWidth(0) leftFrame.setFrameStyle(QtGui.QFrame.Panel) leftFrameLayout.setContentsMargins(0,0,5,0) # Left frame contents self.viewMain = GraphicsLayoutWidget() # A GraphicsLayout within a GraphicsView leftFrameLayout.addWidget(self.viewMain) self.viewMain.setMinimumSize(200,200) self.vb = MultiRoiViewBox(lockAspect=True,enableMenu=True) self.viewMain.addItem(self.vb) self.vb.disableAutoRange() # Right frame self.sidePanel = SidePanel(self) # UI window (containing left and right frames) UIwindow = QtGui.QWidget(self) UIwindowLayout = QtGui.QHBoxLayout() UIwindowSplitter = QtGui.QSplitter(QtCore.Qt.Horizontal) UIwindowLayout.addWidget(UIwindowSplitter) UIwindow.setLayout(UIwindowLayout) self.setCentralWidget(UIwindow) UIwindowSplitter.addWidget(leftFrame) UIwindowSplitter.addWidget(self.sidePanel) # Application window self.setWindowTitle('BMDanalyse') self.setWindowIcon(self.icons['BMDanalyseIcon']) self.setMinimumSize(600,500) self.resize(self.minimumSize()) # Window menus self.createMenus() self.createActions() def createMenus(self): # Menus menubar = self.menuBar() self.fileMenu = menubar.addMenu('&File') self.imageMenu = menubar.addMenu('&Images') self.roiMenu = menubar.addMenu('&ROIs') self.submenu = self.roiMenu.addMenu(self.icons['roiAddIcon'],"Add ROI") self.analyseMenu = menubar.addMenu('&Analysis') self.aboutMenu = menubar.addMenu('A&bout') def createActions(self): # Actions for File menu self.exitAct = QtGui.QAction("&Quit", self, shortcut="Ctrl+Q",statusTip="Exit the application") self.exitAct.triggered[()].connect(self.close) self.fileMenu.addAction(self.exitAct) # Actions for Images menu self.loadImageAct = QtGui.QAction(self.icons['imageAddIcon'], "&Load image(s)", self, shortcut="Ctrl+L") self.removeImageAct = QtGui.QAction(self.icons['imageRemIcon'], "&Remove current image", self, shortcut="Ctrl+X") imageMenuActions = [self.loadImageAct,self.removeImageAct] imageMenuActFuncs = [self.loadImages,self.removeImage] for i in xrange(len(imageMenuActions)): action = imageMenuActions[i] function = imageMenuActFuncs[i] action.triggered[()].connect(function) self.imageMenu.addAction(self.loadImageAct) self.imageMenu.addAction(self.removeImageAct) # Actions for ROI menu self.addROIRectAct = QtGui.QAction("Rectangular",self.submenu) self.addROIPolyAct = QtGui.QAction("Polygon",self.submenu) self.addROIRectAct.triggered[()].connect(self.vb.addROI) self.addROIPolyAct.triggered[()].connect(self.vb.addPolyRoiRequest) self.submenu.addAction(self.addROIRectAct) self.submenu.addAction(self.addROIPolyAct) self.addROIRectAct.setIcon(self.icons['roiRectIcon']) self.addROIPolyAct.setIcon(self.icons['roiPolyIcon']) self.addROIRectAct.setShortcut("Ctrl+Shift+R") self.addROIPolyAct.setShortcut("Ctrl+Shift+P") self.loadRoiAct = QtGui.QAction(self.icons['roiLoadIcon'], "L&oad ROI", self, shortcut="Ctrl+O") self.copyRoiAct = QtGui.QAction(self.icons['roiCopyIcon'], "&Copy ROI", self, shortcut="Ctrl+C") self.saveRoiAct = QtGui.QAction(self.icons['roiSaveIcon'], "&Save ROI", self, shortcut="Ctrl+S") self.remRoiAct = QtGui.QAction(self.icons['roiRemIcon'] , "&Remove ROI", self, shortcut="Ctrl+D") roiMenuActions = [self.loadRoiAct,self.copyRoiAct,self.saveRoiAct,self.remRoiAct] roiMenuActFuncs = [self.vb.loadROI,self.vb.copyROI,self.vb.saveROI,self.vb.removeROI] for i in xrange(len(roiMenuActions)): action = roiMenuActions[i] function = roiMenuActFuncs[i] action.triggered[()].connect(function) self.roiMenu.addAction(action) # Actions for Analyse menu self.roiAnalysisAct = QtGui.QAction("&ROI analysis", self.viewMain, shortcut="Ctrl+R",triggered=self.getBMD) self.imgAnalysisAct = QtGui.QAction("&Image analysis", self.viewMain, shortcut="Ctrl+I",triggered=self.imageAnalysis) self.analyseMenu.addAction(self.roiAnalysisAct) self.analyseMenu.addAction(self.imgAnalysisAct) # Actions for self.aboutAct = QtGui.QAction("&About", self.viewMain, shortcut='F1', triggered=self.onAbout) self.aboutMenu.addAction(self.aboutAct) def setupSignals(self): """ Setup signals """ self.sidePanel.imageFileList.itemSelectionChanged.connect(self.getImageToDisplay) self.sidePanel.buttImageAdd.clicked.connect(self.loadImages) self.sidePanel.buttImageRem.clicked.connect(self.removeImage) self.sidePanel.buttImageUp.clicked.connect(self.sidePanel.moveImageUp) self.sidePanel.buttImageDown.clicked.connect(self.sidePanel.moveImageDown) self.sidePanel.roiMenu.button1.clicked[()].connect(self.vb.addROI) self.sidePanel.roiMenu.button2.clicked[()].connect(self.vb.addPolyRoiRequest) self.sidePanel.buttRoiCopy.clicked[()].connect(self.vb.copyROI) self.sidePanel.buttRoiRem.clicked.connect(self.vb.removeROI) self.sidePanel.buttRoiLoad.clicked.connect(self.vb.loadROI) self.sidePanel.buttRoiSave.clicked.connect(self.vb.saveROI) self.sidePanel.buttRoiAnalysis.clicked.connect(self.getBMD) self.sidePanel.buttImgAnalysis.clicked.connect(self.imageAnalysis) def onAbout(self): """ About BMDanalyse message""" author ='Michael Hogg' date ='2016' version = self.__version__ QtGui.QMessageBox.about(self, 'About BMDanalyse', """ <b>BMDanalyse</b> <p>A simple program for the analysis of a time series of Bone Mineral Density (BMD) images.</p> <p>Used to evaluate the bone gain / loss in a number of regions of interest (ROIs) over time, typically due to bone remodelling as a result of stress shielding around an orthopaedic implant.</p> <p><table border="0" width="150"> <tr> <td>Author:</td> <td>%s</td> </tr> <tr> <td>Version:</td> <td>%s</td> </tr> <tr> <td>Date:</td> <td>%s</td> </tr> </table></p> """ % (author,version,date)) def loadImages(self): """ Load an image to be analysed """ newImages = {} fileNames = QtGui.QFileDialog.getOpenFileNames(self, self.tr("Load images"),QtCore.QDir.currentPath()) # Fix for PySide. PySide doesn't support QStringList types. PyQt4 getOpenFileNames returns a QStringList, whereas PySide # returns a type (the first entry being the list of filenames). if isinstance(fileNames,types.TupleType): fileNames = fileNames[0] if hasattr(QtCore,'QStringList') and isinstance(fileNames, QtCore.QStringList): fileNames = [str(i) for i in fileNames] if len(fileNames)>0: for fileName in fileNames: if fileName!='': img = Image.open(str(fileName)) imgarr = np.array(img.convert('L')) # Convert to 8-bit imgarr = imgarr.swapaxes(0,1) imgarr = imgarr[:,::-1] newImages[fileName] = imgarr # Add filenames to list widget. Only add new filenames. If filename exists aready, then # it will not be added, but data will be updated for fileName in sorted(newImages.keys()): if not self.imageFiles.has_key(fileName): self.sidePanel.addImageToList(fileName) self.imageFiles[fileName] = newImages[fileName] # Show image in Main window self.vb.enableAutoRange() if self.sidePanel.imageFileList.currentRow()==-1: self.sidePanel.imageFileList.setCurrentRow(0) self.showImage(str(self.sidePanel.imageFileList.currentItem().text())) self.vb.disableAutoRange() def removeImage(self): """ Remove image from sidePanel imageFileList """ # Return if there is no image to remove if self.vb.img is None: return # Get current image in sidePanel imageFileList and remove from list currentRow = self.sidePanel.imageFileList.currentRow() image = self.sidePanel.imageFileList.takeItem(currentRow) imageName = str(image.text()) # Delete key and value from dictionary if imageName!='': del self.imageFiles[imageName] # Get image item in imageFileList to replace deleted image if self.sidePanel.imageFileList.count()==0: self.vb.enableAutoRange() self.vb.removeItem(self.vb.img) self.vb.showImage(None) self.vb.disableAutoRange() else: currentRow = self.sidePanel.imageFileList.currentRow() imageName = str(self.sidePanel.imageFileList.item(currentRow).text()) self.showImage(imageName) def showImage(self,imageFilename): """ Shows image in main view """ self.arr = self.imageFiles[imageFilename] self.vb.showImage(self.arr) def getImageToDisplay(self): """ Get current item in file list and display in main view""" try: imageFilename = str(self.sidePanel.imageFileList.currentItem().text()) except: pass else: self.showImage(imageFilename) def getBMD(self): """ Get change in BMD over time (e.g. for each image) for all ROIs. Revised function that converts the list of images into a 3D array and then uses the relative position of the ROIs to the current image, self.vb.img, to get the average BMD value e.g. it doesn't use setImage to change the image in the view. This requires that all images are the same size and in the same position. """ # Return if there is no image or rois in view if self.vb.img is None or len(self.vb.rois)==0: return # Collect all images into a 3D array imageFilenames = self.sidePanel.getListOfImages() images = [self.imageFiles[str(name.text())] for name in imageFilenames] imageData = np.dstack(images) # Doesn't work correctly if images are not all the same shape numImages = len(images) # Get BMD across image stack for each ROI numROIs = len(self.vb.rois) BMD = np.zeros((numImages,numROIs),dtype=float) self.roiNames = [] for i in xrange(numROIs): roi = self.vb.rois[i] self.roiNames.append(roi.name) arrRegion = roi.getArrayRegion(imageData,self.vb.img, axes=(0,1)) avgROIvalue = arrRegion.mean(axis=0).mean(axis=0) BMD[:,i] = avgROIvalue # Calculate the BMD change (percentage of original) tol = 1.0e-06 for i in xrange(numROIs): if abs(BMD[0,i])<tol: BMD[:,i] = 100. else: BMD[:,i] = BMD[:,i] / BMD[0,i] * 100. self.BMDchange = BMD-100. if self.timeData is None or self.timeData.size!=numImages: self.timeData = np.arange(numImages,dtype=float) # Plot results self.showResults() def imageAnalysis(self): # Generate images of BMD change if self.vb.img is None: return self.showImageWin() def sliderValueChanged(self,value): self.imageWin.sliderLabel.setText('BMD change: >= %d %s' % (value,'%')) self.setLookupTable(value) self.imageWin.vb.img2.setLookupTable(self.lut) self.imageWin.vb.img2.setLevels([0,255]) def setLookupTable(self,val): lut = [] for i in range(256): if i > 127+val: lut.append(matplotlib.cm.jet(255)) elif i < 127-val: lut.append(matplotlib.cm.jet(0)) else: lut.append((0.0,0.0,0.0,0.0)) lut = np.array(lut)*255 self.lut = np.array(lut,dtype=np.ubyte) def createImageWin(self): self.buttMinimumSize = QtCore.QSize(70,36) self.iconSize = QtCore.QSize(24,24) if self.imageWin==None: self.imageWin = QtGui.QDialog(self, QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint | \ QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowMaximizeButtonHint) self.imageWin.setWindowTitle('BMDanalyse') self.imageWin.setWindowIcon(self.icons['BMDanalyseIcon']) self.imageWin.setMinimumSize(250,500) self.imageWin.resize(self.imageWin.minimumSize()) # Create viewBox self.imageWin.glw = GraphicsLayoutWidget() # A GraphicsLayout within a GraphicsView self.imageWin.vb = ImageAnalysisViewBox(lockAspect=True,enableMenu=True) self.imageWin.vb.disableAutoRange() self.imageWin.glw.addItem(self.imageWin.vb) arr = self.imageFiles.values()[0] self.imageWin.vb.img1 = ImageItem(arr,autoRange=False,autoLevels=False) self.imageWin.vb.addItem(self.imageWin.vb.img1) self.imageWin.vb.img2 = ImageItem(None,autoRange=False,autoLevels=False) self.imageWin.vb.addItem(self.imageWin.vb.img2) self.imageWin.vb.autoRange() lut = [ [ int(255*val) for val in matplotlib.cm.gray(i)[:3] ] for i in xrange(256) ] lut = np.array(lut,dtype=np.ubyte) self.imageWin.vb.img1.setLookupTable(lut) # Label to show index of current image label self.imageCurrCont = QtGui.QFrame() self.imageCurrCont.setLineWidth(2) self.imageCurrCont.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Raised) self.imageCurrCont.setMinimumWidth(70) self.imageWin.currLabel = QtGui.QLabel("") self.imageWin.currLabel.setAlignment(QtCore.Qt.AlignHCenter) imageCurrContLayout = QtGui.QHBoxLayout() imageCurrContLayout.addWidget(self.imageWin.currLabel) self.imageCurrCont.setLayout(imageCurrContLayout) # Create buttons to select images self.imageWin.buttCont = QtGui.QWidget() self.imageWin.buttPrev = QtGui.QPushButton(self.icons['imagePrevIcon'],"") self.imageWin.buttNext = QtGui.QPushButton(self.icons['imageNextIcon'],"") self.buttLayout = QtGui.QHBoxLayout() self.buttLayout.addStretch(1) self.buttLayout.addWidget(self.imageWin.buttPrev) self.buttLayout.addWidget(self.imageCurrCont) self.buttLayout.addWidget(self.imageWin.buttNext) self.buttLayout.addStretch(1) self.imageWin.buttCont.setLayout(self.buttLayout) self.imageWin.buttPrev.setMinimumSize(self.buttMinimumSize) self.imageWin.buttNext.setMinimumSize(self.buttMinimumSize) self.imageWin.buttPrev.setIconSize(self.iconSize) self.imageWin.buttNext.setIconSize(self.iconSize) self.buttLayout.setContentsMargins(0,5,0,5) self.imageWin.buttPrev.clicked.connect(self.prevImage) self.imageWin.buttNext.clicked.connect(self.nextImage) # Create slider self.imageWin.sliderCon = QtGui.QWidget() self.imageWin.slider = QtGui.QSlider(self) self.imageWin.slider.setOrientation(QtCore.Qt.Horizontal) self.imageWin.slider.setMinimum(1) self.imageWin.slider.setMaximum(100) self.imageWin.slider.setMinimumWidth(100) self.imageWin.slider.valueChanged.connect(self.sliderValueChanged) self.imageWin.sliderLabel = QtGui.QLabel('1') self.imageWin.sliderLabel.setMinimumWidth(120) self.sliderLayout = QtGui.QHBoxLayout() self.sliderLayout.addStretch(1) self.sliderLayout.addWidget(self.imageWin.sliderLabel) self.sliderLayout.addWidget(self.imageWin.slider) self.sliderLayout.addStretch(1) self.imageWin.sliderCon.setLayout(self.sliderLayout) self.sliderLayout.setContentsMargins(0,0,0,5) # Format image window self.imageWinLayout = QtGui.QVBoxLayout() self.imageWinLayout.addWidget(self.imageWin.glw) self.imageWinLayout.addWidget(self.imageWin.buttCont) self.imageWinLayout.addWidget(self.imageWin.sliderCon) self.imageWin.setLayout(self.imageWinLayout) self.imageWin.imagesRGB = None # Show self.imageWin.show() self.imageWin.slider.setValue(10) self.sliderValueChanged(10) self.imageWinIndex = 0 def prevImage(self): minIndex = 0 currIndex = self.imageWinIndex prevIndex = currIndex - 1 self.imageWinIndex = max(prevIndex,minIndex) self.updateImageWin() def nextImage(self): numImages = len(self.imageFiles) maxIndex = numImages - 1 currIndex = self.imageWinIndex nextIndex = currIndex + 1 self.imageWinIndex = min(nextIndex,maxIndex) self.updateImageWin() def updateImageWin(self): imageFilenames = self.sidePanel.getListOfImages() imageName = imageFilenames[self.imageWinIndex] self.imageWin.vb.img1.setImage(self.imageFiles[str(imageName.text())],autoLevels=False) self.imageWin.vb.img2.setImage(self.imageWin.imagesRGB[self.imageWinIndex],autoLevels=False) self.imageWin.currLabel.setText("%i / %i" % (self.imageWinIndex+1,len(imageFilenames))) def showImageWin(self): self.createImageWin() self.imagesBMDpercentChange() self.updateImageWin() def imagesBMDpercentChange(self): # Get image arrays and convert to an array of floats imageFilenames = self.sidePanel.getListOfImages() images = [ self.imageFiles[str(name.text())] for name in imageFilenames ] imagesConv = [] for img in images: image = img.copy() image[np.where(image==0)] = 1 image = image.astype(np.float) imagesConv.append(image) # Calculate percentage change and set with limits -100% to +100% imagesPercCh = [] imageInitial = imagesConv[0] for image in imagesConv: imagePercCh = (image-imageInitial)/imageInitial*100. imagePercCh[np.where(imagePercCh> 100.)] = 100. imagePercCh[np.where(imagePercCh<-100.)] = -100. imagesPercCh.append(imagePercCh) numImages = len(imagesPercCh) self.imageWin.imagesRGB = [] for i in xrange(numImages): image = imagesPercCh[i] sx,sy = image.shape imageRGB = image*(255/200.)+(255/2.) self.imageWin.imagesRGB.append(imageRGB) def BMDtoCSVfile(self): """ Write BMD change to csv file """ fileName = QtGui.QFileDialog.getSaveFileName(None,self.tr("Export to CSV"),QtCore.QDir.currentPath(),self.tr("CSV (*.csv)")) # Fix for PyQt/PySide compatibility. PyQt returns a QString, whereas PySide returns a tuple (first entry is filename as string) if isinstance(fileName,types.TupleType): fileName = fileName[0] if hasattr(QtCore,'QString') and isinstance(fileName, QtCore.QString): fileName = str(fileName) if not fileName=='': textFile = open(fileName,'w') numFrames, numROIs = self.BMDchange.shape roiNames = self.roiNames header = "%10s," % 'Time' header += ((numROIs-1)*'%10s,'+'%10s\n') % tuple(roiNames) textFile.write(header) for i in xrange(numFrames): textFile.write('%10.1f,' % self.timeData[i]) for j in xrange(numROIs): if j<numROIs-1: fmt = '%10.3f,' else: fmt = '%10.3f\n' textFile.write(fmt % self.BMDchange[i,j]) textFile.close() def showResults(self,): """ Plots BMD change using matplotlib """ # Create plot window if self.plotWin==None: self.plotWin = QtGui.QDialog(self, QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint | \ QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowMaximizeButtonHint) self.plotWin.setWindowTitle('BMDanalyse') self.plotWin.setWindowIcon(self.icons['BMDanalyseIcon']) self.plotWin.setMinimumSize(600,500) self.plotWin.resize(self.minimumSize()) # Create Matplotlib widget self.mplw = MatplotlibWidget(size=(5,6)) self.fig = self.mplw.getFigure() self.editDataButton = QtGui.QPushButton('Edit plot') self.exportCSVButton = QtGui.QPushButton('Export data') self.mplw.toolbar.addWidget(self.editDataButton) self.mplw.toolbar.addWidget(self.exportCSVButton) self.editDataButton.clicked.connect(self.showEditBox) self.exportCSVButton.clicked.connect(self.BMDtoCSVfile) # Format plot window self.plotWinLayout = QtGui.QVBoxLayout() self.plotWinLayout.addWidget(self.mplw) self.plotWin.setLayout(self.plotWinLayout) self.createFigure() self.plotWin.show() self.mplw.draw() def createFigure(self): """ Creates plot of results """ self.ax1 = self.fig.add_subplot(111) self.ax1.clear() self.fig.subplots_adjust(bottom=0.15,top=0.85,left=0.15,right=0.925) numFrames, numROIs = self.BMDchange.shape t = self.timeData # Plot data for i in xrange(numROIs): roiname = self.roiNames[i] self.ax1.plot(t,self.BMDchange[:,i],'-o',label=roiname,linewidth=2.0) kwargs = dict(y=1.05) # Or kwargs = {'y':1.05} self.ax1.set_title('Change in Bone Mineral Density over time',fontsize=14,fontweight='roman',**kwargs) self.ax1.set_xlabel('Time',fontsize=10) self.ax1.set_ylabel('Change in BMD (%)',fontsize=10) self.ax1.legend(loc=0) matplotlib.pyplot.setp(self.ax1.get_xmajorticklabels(), fontsize=10) matplotlib.pyplot.setp(self.ax1.get_ymajorticklabels(), fontsize=10) matplotlib.pyplot.setp(self.ax1.get_legend().get_texts(),fontsize=10) self.ax1.grid() def fillEditBox(self): rows,cols = self.BMDchange.shape for i in xrange(rows): itmValue = '%.2f' % self.timeData[i] itm = QtGui.QTableWidgetItem(itmValue) self.tableResults.setItem(i,0,itm) for j in xrange(cols): itmValue = '%.2f' % self.BMDchange[i,j] itm = QtGui.QTableWidgetItem(itmValue) self.tableResults.setItem(i,j+1,itm) def showEditBox(self): self.plotWin.editBox = QtGui.QDialog(self.plotWin, QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint) self.plotWin.editBox.setWindowIcon(self.icons['BMDanalyseIcon']) self.plotWin.editBox.setWindowTitle('BMDanalyse') self.plotWin.editBox.setModal(True) # Add table layout = QtGui.QVBoxLayout() layout.setContentsMargins(10,10,10,10) layout.setSpacing(20) rows,cols = self.BMDchange.shape self.tableResults = TableWidget(rows,cols+1,self.plotWin.editBox) self.tableResults.verticalHeader().setVisible(True) # Set headers self.tableResults.setHorizontalHeaderItem(0,QtGui.QTableWidgetItem('Time')) for i in xrange(cols): header = QtGui.QTableWidgetItem(self.roiNames[i]) self.tableResults.setHorizontalHeaderItem(i+1,header) # Add values to table self.fillEditBox() # Set layout layout.addWidget(self.tableResults) self.buttonsFrame = QtGui.QFrame() self.buttonsLayout = QtGui.QHBoxLayout() self.buttonReset = QtGui.QPushButton('Reset') self.buttonSave = QtGui.QPushButton('Save') self.buttonClose = QtGui.QPushButton('Cancel') self.buttonReset.setFixedWidth(50) self.buttonSave.setFixedWidth(50) self.buttonClose.setFixedWidth(50) self.buttonClose.clicked.connect(self.plotWin.editBox.close) self.buttonSave.clicked.connect(self.updateTableValues) self.buttonReset.clicked.connect(self.fillEditBox) self.buttonsLayout.addStretch(1) self.buttonsLayout.addWidget(self.buttonReset) self.buttonsLayout.addWidget(self.buttonSave) self.buttonsLayout.addWidget(self.buttonClose) self.buttonsLayout.setContentsMargins(0,0,0,0) self.buttonsFrame.setLayout(self.buttonsLayout) layout.addWidget(self.buttonsFrame) self.plotWin.editBox.setLayout(layout) self.plotWin.editBox.setMaximumSize(layout.sizeHint()) self.plotWin.editBox.show() def updateTableValues(self): # Create temporary arrays timeData = self.timeData.copy() BMDchange = self.BMDchange.copy() # Put the values from the tables into the temporary arrays rows = self.tableResults.rowCount() cols = self.tableResults.columnCount() for r in xrange(rows): for c in xrange(cols): item = self.tableResults.item(r,c) itemValue = float(item.text()) if c==0: timeData[r] = itemValue else: BMDchange[r,c-1] = itemValue # Check that time values are in increasing order. If so, then update arrays if any(np.diff(timeData)<=0): self.errorMessage = QtGui.QMessageBox() self.errorMessage.setWindowIcon(self.icons['BMDanalyseIcon']) self.errorMessage.setWindowTitle('BMDanalyse') self.errorMessage.setText('Input error: Time values should be in order of increasing value') self.errorMessage.setIcon(QtGui.QMessageBox.Warning) self.errorMessage.open() else: self.timeData = timeData self.BMDchange = BMDchange self.createFigure() self.mplw.draw() self.plotWin.editBox.close()
def __init__(self): GraphicsLayoutWidget.__init__(self) uic.loadUi(tableUIFile, self) self._initTable()
def setupUi(self, WidgetAnalyze): WidgetAnalyze.setObjectName("WidgetAnalyze") WidgetAnalyze.resize(348, 528) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(WidgetAnalyze.sizePolicy().hasHeightForWidth()) WidgetAnalyze.setSizePolicy(sizePolicy) WidgetAnalyze.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.verticalLayout_2 = QtWidgets.QVBoxLayout(WidgetAnalyze) self.verticalLayout_2.setObjectName("verticalLayout_2") self.horizontalLayout_Source = QtWidgets.QHBoxLayout() self.horizontalLayout_Source.setObjectName("horizontalLayout_Source") self.labelSource = QtWidgets.QLabel(WidgetAnalyze) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.labelSource.sizePolicy().hasHeightForWidth()) self.labelSource.setSizePolicy(sizePolicy) self.labelSource.setTextFormat(QtCore.Qt.PlainText) self.labelSource.setObjectName("labelSource") self.horizontalLayout_Source.addWidget(self.labelSource) self.comboBoxSource = QtWidgets.QComboBox(WidgetAnalyze) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.comboBoxSource.sizePolicy().hasHeightForWidth()) self.comboBoxSource.setSizePolicy(sizePolicy) self.comboBoxSource.setObjectName("comboBoxSource") self.horizontalLayout_Source.addWidget(self.comboBoxSource) self.verticalLayout_2.addLayout(self.horizontalLayout_Source) self.horizontalLayout_ROI = QtWidgets.QHBoxLayout() self.horizontalLayout_ROI.setObjectName("horizontalLayout_ROI") self.labelROIs = QtWidgets.QLabel(WidgetAnalyze) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.labelROIs.sizePolicy().hasHeightForWidth()) self.labelROIs.setSizePolicy(sizePolicy) self.labelROIs.setTextFormat(QtCore.Qt.PlainText) self.labelROIs.setObjectName("labelROIs") self.horizontalLayout_ROI.addWidget(self.labelROIs) self.comboBoxROIs = QtWidgets.QComboBox(WidgetAnalyze) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.comboBoxROIs.sizePolicy().hasHeightForWidth()) self.comboBoxROIs.setSizePolicy(sizePolicy) self.comboBoxROIs.setCurrentText("") self.comboBoxROIs.setObjectName("comboBoxROIs") self.horizontalLayout_ROI.addWidget(self.comboBoxROIs) self.verticalLayout_2.addLayout(self.horizontalLayout_ROI) self.horizontalLayout_Signal = QtWidgets.QHBoxLayout() self.horizontalLayout_Signal.setObjectName("horizontalLayout_Signal") self.labelSignal = QtWidgets.QLabel(WidgetAnalyze) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.labelSignal.sizePolicy().hasHeightForWidth()) self.labelSignal.setSizePolicy(sizePolicy) self.labelSignal.setTextFormat(QtCore.Qt.PlainText) self.labelSignal.setObjectName("labelSignal") self.horizontalLayout_Signal.addWidget(self.labelSignal) self.comboBoxSignal = QtWidgets.QComboBox(WidgetAnalyze) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.comboBoxSignal.sizePolicy().hasHeightForWidth()) self.comboBoxSignal.setSizePolicy(sizePolicy) self.comboBoxSignal.setObjectName("comboBoxSignal") self.horizontalLayout_Signal.addWidget(self.comboBoxSignal) self.verticalLayout_2.addLayout(self.horizontalLayout_Signal) self.horizontalLayout_Analysis = QtWidgets.QHBoxLayout() self.horizontalLayout_Analysis.setObjectName("horizontalLayout_Analysis") self.labelAnalysis = QtWidgets.QLabel(WidgetAnalyze) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.labelAnalysis.sizePolicy().hasHeightForWidth()) self.labelAnalysis.setSizePolicy(sizePolicy) self.labelAnalysis.setTextFormat(QtCore.Qt.PlainText) self.labelAnalysis.setObjectName("labelAnalysis") self.horizontalLayout_Analysis.addWidget(self.labelAnalysis) self.comboBoxAnalysis = QtWidgets.QComboBox(WidgetAnalyze) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.comboBoxAnalysis.sizePolicy().hasHeightForWidth()) self.comboBoxAnalysis.setSizePolicy(sizePolicy) self.comboBoxAnalysis.setObjectName("comboBoxAnalysis") self.comboBoxAnalysis.addItem("") self.horizontalLayout_Analysis.addWidget(self.comboBoxAnalysis) self.verticalLayout_2.addLayout(self.horizontalLayout_Analysis) self.splitter = QtWidgets.QSplitter(WidgetAnalyze) self.splitter.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setObjectName("splitter") self.tabWidgetAnalysisSteps = QtWidgets.QTabWidget(self.splitter) self.tabWidgetAnalysisSteps.setEnabled(True) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.tabWidgetAnalysisSteps.sizePolicy().hasHeightForWidth()) self.tabWidgetAnalysisSteps.setSizePolicy(sizePolicy) self.tabWidgetAnalysisSteps.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.tabWidgetAnalysisSteps.setTabPosition(QtWidgets.QTabWidget.North) self.tabWidgetAnalysisSteps.setDocumentMode(False) self.tabWidgetAnalysisSteps.setTabBarAutoHide(False) self.tabWidgetAnalysisSteps.setObjectName("tabWidgetAnalysisSteps") self.tabTimeSlice = QtWidgets.QWidget() self.tabTimeSlice.setEnabled(True) self.tabTimeSlice.setObjectName("tabTimeSlice") self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.tabTimeSlice) self.verticalLayout_3.setObjectName("verticalLayout_3") self.horizontalLayout_7 = QtWidgets.QHBoxLayout() self.horizontalLayout_7.setObjectName("horizontalLayout_7") self.checkBoxTimeAll = QtWidgets.QCheckBox(self.tabTimeSlice) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.checkBoxTimeAll.sizePolicy().hasHeightForWidth()) self.checkBoxTimeAll.setSizePolicy(sizePolicy) self.checkBoxTimeAll.setChecked(False) self.checkBoxTimeAll.setObjectName("checkBoxTimeAll") self.horizontalLayout_7.addWidget(self.checkBoxTimeAll) spacerItem = QtWidgets.QSpacerItem(13, 20, QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_7.addItem(spacerItem) self.formLayout_4 = QtWidgets.QFormLayout() self.formLayout_4.setFormAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.formLayout_4.setObjectName("formLayout_4") self.startLabel = QtWidgets.QLabel(self.tabTimeSlice) self.startLabel.setObjectName("startLabel") self.formLayout_4.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.startLabel) self.startSpinBox = QtWidgets.QSpinBox(self.tabTimeSlice) self.startSpinBox.setEnabled(True) self.startSpinBox.setMinimumSize(QtCore.QSize(60, 0)) self.startSpinBox.setMinimum(1) self.startSpinBox.setMaximum(999999) self.startSpinBox.setObjectName("startSpinBox") self.formLayout_4.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.startSpinBox) self.endSpinBox = QtWidgets.QSpinBox(self.tabTimeSlice) self.endSpinBox.setMinimumSize(QtCore.QSize(60, 0)) self.endSpinBox.setMinimum(1) self.endSpinBox.setMaximum(999999) self.endSpinBox.setObjectName("endSpinBox") self.formLayout_4.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.endSpinBox) self.endLabel = QtWidgets.QLabel(self.tabTimeSlice) self.endLabel.setObjectName("endLabel") self.formLayout_4.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.endLabel) self.horizontalLayout_7.addLayout(self.formLayout_4) self.verticalLayout_3.addLayout(self.horizontalLayout_7) self.buttonBoxTimeSlice = QtWidgets.QDialogButtonBox(self.tabTimeSlice) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.buttonBoxTimeSlice.sizePolicy().hasHeightForWidth()) self.buttonBoxTimeSlice.setSizePolicy(sizePolicy) self.buttonBoxTimeSlice.setStandardButtons(QtWidgets.QDialogButtonBox.Apply) self.buttonBoxTimeSlice.setObjectName("buttonBoxTimeSlice") self.verticalLayout_3.addWidget(self.buttonBoxTimeSlice) self.tabWidgetAnalysisSteps.addTab(self.tabTimeSlice, "") self.tabCondition = QtWidgets.QWidget() self.tabCondition.setObjectName("tabCondition") self.verticalLayout_6 = QtWidgets.QVBoxLayout(self.tabCondition) self.verticalLayout_6.setObjectName("verticalLayout_6") self.horizontalLayout_4 = QtWidgets.QHBoxLayout() self.horizontalLayout_4.setObjectName("horizontalLayout_4") self.formLayoutCondition = QtWidgets.QFormLayout() self.formLayoutCondition.setObjectName("formLayoutCondition") self.signalTypeLabel = QtWidgets.QLabel(self.tabCondition) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.signalTypeLabel.sizePolicy().hasHeightForWidth()) self.signalTypeLabel.setSizePolicy(sizePolicy) self.signalTypeLabel.setObjectName("signalTypeLabel") self.formLayoutCondition.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.signalTypeLabel) self.signalTypeComboBox = QtWidgets.QComboBox(self.tabCondition) self.signalTypeComboBox.setObjectName("signalTypeComboBox") self.signalTypeComboBox.addItem("") self.signalTypeComboBox.addItem("") self.formLayoutCondition.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.signalTypeComboBox) self.roiCalculationLabel = QtWidgets.QLabel(self.tabCondition) self.roiCalculationLabel.setObjectName("roiCalculationLabel") self.formLayoutCondition.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.roiCalculationLabel) self.roiCalculationComboBox = QtWidgets.QComboBox(self.tabCondition) self.roiCalculationComboBox.setObjectName("roiCalculationComboBox") self.roiCalculationComboBox.addItem("") self.formLayoutCondition.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.roiCalculationComboBox) self.horizontalLayout_4.addLayout(self.formLayoutCondition) self.verticalLayout_5 = QtWidgets.QVBoxLayout() self.verticalLayout_5.setObjectName("verticalLayout_5") self.groupBoxFilter = QtWidgets.QGroupBox(self.tabCondition) self.groupBoxFilter.setCheckable(True) self.groupBoxFilter.setObjectName("groupBoxFilter") self.formLayout = QtWidgets.QFormLayout(self.groupBoxFilter) self.formLayout.setObjectName("formLayout") self.filterFreqLabel = QtWidgets.QLabel(self.groupBoxFilter) self.filterFreqLabel.setWordWrap(True) self.filterFreqLabel.setObjectName("filterFreqLabel") self.formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.filterFreqLabel) self.filterFreqSpinBox = QtWidgets.QSpinBox(self.groupBoxFilter) self.filterFreqSpinBox.setMinimum(1) self.filterFreqSpinBox.setMaximum(200) self.filterFreqSpinBox.setProperty("value", 50) self.filterFreqSpinBox.setObjectName("filterFreqSpinBox") self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.filterFreqSpinBox) self.verticalLayout_5.addWidget(self.groupBoxFilter) self.groupBoxDetrend = QtWidgets.QGroupBox(self.tabCondition) self.groupBoxDetrend.setCheckable(True) self.groupBoxDetrend.setObjectName("groupBoxDetrend") self.formLayout_2 = QtWidgets.QFormLayout(self.groupBoxDetrend) self.formLayout_2.setObjectName("formLayout_2") self.detrendDegreeLabel = QtWidgets.QLabel(self.groupBoxDetrend) self.detrendDegreeLabel.setWordWrap(True) self.detrendDegreeLabel.setObjectName("detrendDegreeLabel") self.formLayout_2.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.detrendDegreeLabel) self.detrendDegreeSpinBox = QtWidgets.QSpinBox(self.groupBoxDetrend) self.detrendDegreeSpinBox.setMinimum(1) self.detrendDegreeSpinBox.setMaximum(4) self.detrendDegreeSpinBox.setProperty("value", 2) self.detrendDegreeSpinBox.setObjectName("detrendDegreeSpinBox") self.formLayout_2.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.detrendDegreeSpinBox) self.verticalLayout_5.addWidget(self.groupBoxDetrend) self.horizontalLayout_4.addLayout(self.verticalLayout_5) self.verticalLayout_6.addLayout(self.horizontalLayout_4) self.buttonBoxCondition = QtWidgets.QDialogButtonBox(self.tabCondition) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.buttonBoxCondition.sizePolicy().hasHeightForWidth()) self.buttonBoxCondition.setSizePolicy(sizePolicy) self.buttonBoxCondition.setStandardButtons(QtWidgets.QDialogButtonBox.Apply) self.buttonBoxCondition.setObjectName("buttonBoxCondition") self.verticalLayout_6.addWidget(self.buttonBoxCondition) self.tabWidgetAnalysisSteps.addTab(self.tabCondition, "") self.tabPeakDetect = QtWidgets.QWidget() self.tabPeakDetect.setObjectName("tabPeakDetect") self.verticalLayout = QtWidgets.QVBoxLayout(self.tabPeakDetect) self.verticalLayout.setObjectName("verticalLayout") self.formLayoutPeakDetect = QtWidgets.QFormLayout() self.formLayoutPeakDetect.setObjectName("formLayoutPeakDetect") self.thresholdLabel = QtWidgets.QLabel(self.tabPeakDetect) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.thresholdLabel.sizePolicy().hasHeightForWidth()) self.thresholdLabel.setSizePolicy(sizePolicy) self.thresholdLabel.setObjectName("thresholdLabel") self.formLayoutPeakDetect.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.thresholdLabel) self.thresholdDoubleSpinBox = QtWidgets.QDoubleSpinBox(self.tabPeakDetect) self.thresholdDoubleSpinBox.setMinimum(0.01) self.thresholdDoubleSpinBox.setMaximum(0.99) self.thresholdDoubleSpinBox.setSingleStep(0.01) self.thresholdDoubleSpinBox.setProperty("value", 0.72) self.thresholdDoubleSpinBox.setObjectName("thresholdDoubleSpinBox") self.formLayoutPeakDetect.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.thresholdDoubleSpinBox) self.lockoutTimeLabel = QtWidgets.QLabel(self.tabPeakDetect) self.lockoutTimeLabel.setObjectName("lockoutTimeLabel") self.formLayoutPeakDetect.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.lockoutTimeLabel) self.lockoutTimeSpinBox = QtWidgets.QSpinBox(self.tabPeakDetect) self.lockoutTimeSpinBox.setMinimum(1) self.lockoutTimeSpinBox.setMaximum(3000) self.lockoutTimeSpinBox.setProperty("value", 172) self.lockoutTimeSpinBox.setObjectName("lockoutTimeSpinBox") self.formLayoutPeakDetect.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.lockoutTimeSpinBox) self.verticalLayout.addLayout(self.formLayoutPeakDetect) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setSpacing(0) self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.pushButtonExportTrace = QtWidgets.QPushButton(self.tabPeakDetect) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.pushButtonExportTrace.sizePolicy().hasHeightForWidth()) self.pushButtonExportTrace.setSizePolicy(sizePolicy) self.pushButtonExportTrace.setObjectName("pushButtonExportTrace") self.horizontalLayout_3.addWidget(self.pushButtonExportTrace) self.buttonBoxPeakDetect = QtWidgets.QDialogButtonBox(self.tabPeakDetect) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.buttonBoxPeakDetect.sizePolicy().hasHeightForWidth()) self.buttonBoxPeakDetect.setSizePolicy(sizePolicy) self.buttonBoxPeakDetect.setStandardButtons(QtWidgets.QDialogButtonBox.Apply) self.buttonBoxPeakDetect.setObjectName("buttonBoxPeakDetect") self.horizontalLayout_3.addWidget(self.buttonBoxPeakDetect) self.verticalLayout.addLayout(self.horizontalLayout_3) self.tabWidgetAnalysisSteps.addTab(self.tabPeakDetect, "") self.tabProcess = QtWidgets.QWidget() self.tabProcess.setObjectName("tabProcess") self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.tabProcess) self.verticalLayout_4.setObjectName("verticalLayout_4") self.processTableView = QtWidgets.QTableView(self.tabProcess) self.processTableView.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) self.processTableView.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection) self.processTableView.setObjectName("processTableView") self.verticalLayout_4.addWidget(self.processTableView) self.buttonBoxProcess = QtWidgets.QDialogButtonBox(self.tabProcess) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.buttonBoxProcess.sizePolicy().hasHeightForWidth()) self.buttonBoxProcess.setSizePolicy(sizePolicy) self.buttonBoxProcess.setStandardButtons(QtWidgets.QDialogButtonBox.Apply) self.buttonBoxProcess.setObjectName("buttonBoxProcess") self.verticalLayout_4.addWidget(self.buttonBoxProcess) self.tabWidgetAnalysisSteps.addTab(self.tabProcess, "") self.widgetPreview = GraphicsLayoutWidget(self.splitter) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.widgetPreview.sizePolicy().hasHeightForWidth()) self.widgetPreview.setSizePolicy(sizePolicy) self.widgetPreview.setMinimumSize(QtCore.QSize(70, 200)) self.widgetPreview.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.widgetPreview.setObjectName("widgetPreview") self.verticalLayout_2.addWidget(self.splitter) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.progressBar = QtWidgets.QProgressBar(WidgetAnalyze) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.progressBar.sizePolicy().hasHeightForWidth()) self.progressBar.setSizePolicy(sizePolicy) self.progressBar.setMinimumSize(QtCore.QSize(10, 0)) self.progressBar.setProperty("value", 0) self.progressBar.setTextVisible(False) self.progressBar.setInvertedAppearance(False) self.progressBar.setObjectName("progressBar") self.horizontalLayout.addWidget(self.progressBar) spacerItem1 = QtWidgets.QSpacerItem(20, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem1) self.buttonBoxAnalyze = QtWidgets.QDialogButtonBox(WidgetAnalyze) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.buttonBoxAnalyze.sizePolicy().hasHeightForWidth()) self.buttonBoxAnalyze.setSizePolicy(sizePolicy) self.buttonBoxAnalyze.setOrientation(QtCore.Qt.Horizontal) self.buttonBoxAnalyze.setStandardButtons(QtWidgets.QDialogButtonBox.Discard|QtWidgets.QDialogButtonBox.Ok|QtWidgets.QDialogButtonBox.RestoreDefaults) self.buttonBoxAnalyze.setCenterButtons(False) self.buttonBoxAnalyze.setObjectName("buttonBoxAnalyze") self.horizontalLayout.addWidget(self.buttonBoxAnalyze) self.verticalLayout_2.addLayout(self.horizontalLayout) self.retranslateUi(WidgetAnalyze) self.comboBoxROIs.setCurrentIndex(-1) self.comboBoxSignal.setCurrentIndex(-1) self.tabWidgetAnalysisSteps.setCurrentIndex(1) QtCore.QMetaObject.connectSlotsByName(WidgetAnalyze)
def createImageWin(self): self.buttMinimumSize = QtCore.QSize(70, 36) self.iconSize = QtCore.QSize(24, 24) if self.imageWin == None: self.imageWin = QtGui.QDialog(self, QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint | \ QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowMaximizeButtonHint) self.imageWin.setWindowTitle('BMDanalyse') self.imageWin.setWindowIcon(self.icons['BMDanalyseIcon']) self.imageWin.setMinimumSize(250, 500) self.imageWin.resize(self.imageWin.minimumSize()) # Create viewBox self.imageWin.glw = GraphicsLayoutWidget( ) # A GraphicsLayout within a GraphicsView self.imageWin.vb = ImageAnalysisViewBox(lockAspect=True, enableMenu=True) self.imageWin.vb.disableAutoRange() self.imageWin.glw.addItem(self.imageWin.vb) arr = self.imageFiles.values()[0] self.imageWin.vb.img1 = pg.ImageItem(arr, autoRange=False, autoLevels=False) self.imageWin.vb.addItem(self.imageWin.vb.img1) self.imageWin.vb.img2 = pg.ImageItem(None, autoRange=False, autoLevels=False) self.imageWin.vb.addItem(self.imageWin.vb.img2) self.imageWin.vb.autoRange() lut = [[int(255 * val) for val in matplotlib.cm.gray(i)[:3]] for i in xrange(256)] lut = np.array(lut, dtype=np.ubyte) self.imageWin.vb.img1.setLookupTable(lut) # Label to show index of current image label self.imageCurrCont = QtGui.QFrame() self.imageCurrCont.setLineWidth(2) self.imageCurrCont.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Raised) self.imageCurrCont.setMinimumWidth(70) self.imageWin.currLabel = QtGui.QLabel("") self.imageWin.currLabel.setAlignment(QtCore.Qt.AlignHCenter) imageCurrContLayout = QtGui.QHBoxLayout() imageCurrContLayout.addWidget(self.imageWin.currLabel) self.imageCurrCont.setLayout(imageCurrContLayout) # Create buttons to select images self.imageWin.buttCont = QtGui.QWidget() self.imageWin.buttPrev = QtGui.QPushButton( self.icons['imagePrevIcon'], "") self.imageWin.buttNext = QtGui.QPushButton( self.icons['imageNextIcon'], "") self.buttLayout = QtGui.QHBoxLayout() self.buttLayout.addStretch(1) self.buttLayout.addWidget(self.imageWin.buttPrev) self.buttLayout.addWidget(self.imageCurrCont) self.buttLayout.addWidget(self.imageWin.buttNext) self.buttLayout.addStretch(1) self.imageWin.buttCont.setLayout(self.buttLayout) self.imageWin.buttPrev.setMinimumSize(self.buttMinimumSize) self.imageWin.buttNext.setMinimumSize(self.buttMinimumSize) self.imageWin.buttPrev.setIconSize(self.iconSize) self.imageWin.buttNext.setIconSize(self.iconSize) self.buttLayout.setContentsMargins(0, 5, 0, 5) self.imageWin.buttPrev.clicked.connect(self.prevImage) self.imageWin.buttNext.clicked.connect(self.nextImage) # Create slider self.imageWin.sliderCon = QtGui.QWidget() self.imageWin.slider = QtGui.QSlider(self) self.imageWin.slider.setOrientation(QtCore.Qt.Horizontal) self.imageWin.slider.setMinimum(1) self.imageWin.slider.setMaximum(100) self.imageWin.slider.setMinimumWidth(100) self.imageWin.slider.valueChanged.connect(self.sliderValueChanged) self.imageWin.sliderLabel = QtGui.QLabel('1') self.imageWin.sliderLabel.setMinimumWidth(120) self.sliderLayout = QtGui.QHBoxLayout() self.sliderLayout.addStretch(1) self.sliderLayout.addWidget(self.imageWin.sliderLabel) self.sliderLayout.addWidget(self.imageWin.slider) self.sliderLayout.addStretch(1) self.imageWin.sliderCon.setLayout(self.sliderLayout) self.sliderLayout.setContentsMargins(0, 0, 0, 5) # Format image window self.imageWinLayout = QtGui.QVBoxLayout() self.imageWinLayout.addWidget(self.imageWin.glw) self.imageWinLayout.addWidget(self.imageWin.buttCont) self.imageWinLayout.addWidget(self.imageWin.sliderCon) self.imageWin.setLayout(self.imageWinLayout) self.imageWin.imagesRGB = None # Show self.imageWin.show() self.imageWin.slider.setValue(10) self.sliderValueChanged(10) self.imageWinIndex = 0
class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.loadIcons() self.setupUserInterface() self.setupSignals() self.__version__ = __version__ # Initialise variables self.imageFiles = {} self.timeData = None self.plotWin = None self.imageWin = None self.BMDchange = None self.roiNames = None def loadIcons(self): """ Load icons """ self.icons = dict([ ('BMDanalyseIcon', QtGui.QIcon(os.path.join(absDirPath, "icons", "logo.png"))), ('imageAddIcon', QtGui.QIcon(os.path.join(absDirPath, "icons", "file_add.png"))), ('imageRemIcon', QtGui.QIcon(os.path.join(absDirPath, "icons", "file_delete2.png"))), ('imageDownIcon', QtGui.QIcon(os.path.join(absDirPath, "icons", "arrow-up-2.png"))), ('imageUpIcon', QtGui.QIcon(os.path.join(absDirPath, "icons", "arrow-down-2.png"))), ('imagePrevIcon', QtGui.QIcon(os.path.join(absDirPath, "icons", "arrow-left.png"))), ('imageNextIcon', QtGui.QIcon(os.path.join(absDirPath, "icons", "arrow-right.png"))), ('roiAddIcon', QtGui.QIcon(os.path.join(absDirPath, "icons", "green-add3.png"))), ('roiRectIcon', QtGui.QIcon( os.path.join(absDirPath, "icons", "rectangularIcon.png"))), ('roiPolyIcon', QtGui.QIcon(os.path.join(absDirPath, "icons", "polygonIcon.png"))), ('roiRemIcon', QtGui.QIcon(os.path.join(absDirPath, "icons", "red_delete.png"))), ('roiSaveIcon', QtGui.QIcon(os.path.join(absDirPath, "icons", "filesave.png"))), ('roiCopyIcon', QtGui.QIcon(os.path.join(absDirPath, "icons", "file_copy.png"))), ('roiLoadIcon', QtGui.QIcon(os.path.join(absDirPath, "icons", "opened-folder.png"))) ]) def setupUserInterface(self): """ Initialise the User Interface """ # Left frame leftFrame = QtGui.QFrame() leftFrameLayout = QtGui.QHBoxLayout() leftFrame.setLayout(leftFrameLayout) leftFrame.setLineWidth(0) leftFrame.setFrameStyle(QtGui.QFrame.Panel) leftFrameLayout.setContentsMargins(0, 0, 5, 0) # Left frame contents self.viewMain = GraphicsLayoutWidget( ) # A GraphicsLayout within a GraphicsView leftFrameLayout.addWidget(self.viewMain) self.viewMain.setMinimumSize(200, 200) self.vb = MultiRoiViewBox(lockAspect=True, enableMenu=True) self.viewMain.addItem(self.vb) self.vb.disableAutoRange() # Right frame self.sidePanel = SidePanel(self) # UI window (containing left and right frames) UIwindow = QtGui.QWidget(self) UIwindowLayout = QtGui.QHBoxLayout() UIwindowSplitter = QtGui.QSplitter(QtCore.Qt.Horizontal) UIwindowLayout.addWidget(UIwindowSplitter) UIwindow.setLayout(UIwindowLayout) self.setCentralWidget(UIwindow) UIwindowSplitter.addWidget(leftFrame) UIwindowSplitter.addWidget(self.sidePanel) # Application window self.setWindowTitle('BMDanalyse') self.setWindowIcon(self.icons['BMDanalyseIcon']) self.setMinimumSize(600, 500) self.resize(self.minimumSize()) # Window menus self.createMenus() self.createActions() def createMenus(self): # Menus menubar = self.menuBar() self.fileMenu = menubar.addMenu('&File') self.roiMenu = menubar.addMenu('&ROIs') self.submenu = self.roiMenu.addMenu(self.icons['roiAddIcon'], "Add ROI") self.analyseMenu = menubar.addMenu('&Analyse') self.aboutMenu = menubar.addMenu('A&bout') def createActions(self): # Actions for File menu self.loadImageAct = QtGui.QAction(self.icons['imageAddIcon'], "&Load image(s)", self, shortcut="Ctrl+L") self.removeImageAct = QtGui.QAction(self.icons['imageRemIcon'], "&Remove current image", self, shortcut="Ctrl+X") self.exitAct = QtGui.QAction("&Quit", self, shortcut="Ctrl+Q", statusTip="Exit the application") fileMenuActions = [ self.loadImageAct, self.removeImageAct, self.exitAct ] fileMenuActFuncs = [self.loadImages, self.removeImage, self.close] for i in xrange(len(fileMenuActions)): action = fileMenuActions[i] function = fileMenuActFuncs[i] action.triggered[()].connect(function) self.fileMenu.addAction(self.loadImageAct) self.fileMenu.addAction(self.removeImageAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.exitAct) # Actions for ROI menu # Submenu to add ROIs #self.addROIRectAct = QActionCustom("Rectangular",self.submenu) #self.addROIPolyAct = QActionCustom("Polygon",self.submenu) self.addROIRectAct = QtGui.QAction("Rectangular", self.submenu) self.addROIPolyAct = QtGui.QAction("Polygon", self.submenu) #self.addROIRectAct.clickEvent.connect(self.vb.addROI) #self.addROIPolyAct.clickEvent.connect(self.vb.addPolyRoiRequest) self.addROIRectAct.triggered[()].connect(self.vb.addROI) self.addROIPolyAct.triggered[()].connect(self.vb.addPolyRoiRequest) self.submenu.addAction(self.addROIRectAct) self.submenu.addAction(self.addROIPolyAct) self.addROIRectAct.setIcon(self.icons['roiRectIcon']) self.addROIPolyAct.setIcon(self.icons['roiPolyIcon']) self.addROIRectAct.setShortcut("Ctrl+Shift+R") self.addROIPolyAct.setShortcut("Ctrl+Shift+P") self.loadRoiAct = QtGui.QAction(self.icons['roiLoadIcon'], "L&oad ROI", self, shortcut="Ctrl+O") self.copyRoiAct = QtGui.QAction(self.icons['roiCopyIcon'], "&Copy ROI", self, shortcut="Ctrl+C") self.saveRoiAct = QtGui.QAction(self.icons['roiSaveIcon'], "&Save ROI", self, shortcut="Ctrl+S") self.remRoiAct = QtGui.QAction(self.icons['roiRemIcon'], "&Remove ROI", self, shortcut="Ctrl+D") roiMenuActions = [ self.loadRoiAct, self.copyRoiAct, self.saveRoiAct, self.remRoiAct ] roiMenuActFuncs = [ self.vb.loadROI, self.vb.copyROI, self.vb.saveROI, self.vb.removeROI ] for i in xrange(len(roiMenuActions)): action = roiMenuActions[i] function = roiMenuActFuncs[i] action.triggered[()].connect(function) self.roiMenu.addAction(action) # Actions for Analyse menu self.roiAnalysisAct = QtGui.QAction("&ROI analysis", self.viewMain, shortcut="Ctrl+R", triggered=self.getBMD) self.imgAnalysisAct = QtGui.QAction("&Image analysis", self.viewMain, shortcut="Ctrl+I", triggered=self.imageAnalysis) self.analyseMenu.addAction(self.roiAnalysisAct) self.analyseMenu.addAction(self.imgAnalysisAct) # Actions for self.aboutAct = QtGui.QAction("&About", self.viewMain, shortcut='F1', triggered=self.onAbout) self.aboutMenu.addAction(self.aboutAct) def setupSignals(self): """ Setup signals """ self.sidePanel.imageFileList.itemSelectionChanged.connect( self.getImageToDisplay) self.sidePanel.buttImageAdd.clicked.connect(self.loadImages) self.sidePanel.buttImageRem.clicked.connect(self.removeImage) self.sidePanel.buttImageUp.clicked.connect(self.sidePanel.moveImageUp) self.sidePanel.buttImageDown.clicked.connect( self.sidePanel.moveImageDown) self.sidePanel.roiMenu.button1.clicked[()].connect(self.vb.addROI) self.sidePanel.roiMenu.button2.clicked[()].connect( self.vb.addPolyRoiRequest) self.sidePanel.buttRoiCopy.clicked[()].connect(self.vb.copyROI) self.sidePanel.buttRoiRem.clicked.connect(self.vb.removeROI) self.sidePanel.buttRoiLoad.clicked.connect(self.vb.loadROI) self.sidePanel.buttRoiSave.clicked.connect(self.vb.saveROI) #self.vb.sigROIchanged.connect(self.updateROItools) def onAbout(self): """ About BMDanalyse message""" author = 'Michael Hogg' date = '2012 - 2013' version = self.__version__ QtGui.QMessageBox.about( self, 'About BMDanalyse', """ <b>BMDanalyse</b> <p>A simple program for the analysis of a time series of Bone Mineral Density (BMD) images.</p> <p>Used to evaluate the bone gain / loss in a number of regions of interest (ROIs) over time, typically due to bone remodelling as a result of stress shielding around an orthopaedic implant.</p> <p><table border="0" width="150"> <tr> <td>Author:</td> <td>%s</td> </tr> <tr> <td>Version:</td> <td>%s</td> </tr> <tr> <td>Date:</td> <td>%s</td> </tr> </table></p> """ % (author, version, date)) def updateROItools(self, roi=None): """ Update ROI info box in side panel """ if roi == None: self.sidePanel.updateRoiInfoBox() else: roiState = roi.getState() posx, posy = roiState['pos'] sizex, sizey = roiState['size'] angle = roiState['angle'] name = roi.name pos = '(%.3f, %.3f)' % (posx, posy) size = '(%.3f, %.3f)' % (sizex, sizey) angle = '%.3f' % angle self.sidePanel.updateRoiInfoBox(name, pos, size, angle) def loadImages(self): """ Load an image to be analysed """ newImages = {} fileNames = QtGui.QFileDialog.getOpenFileNames( self, self.tr("Load images"), QtCore.QDir.currentPath()) # Fix for PySide. PySide doesn't support QStringList types. PyQt4 getOpenFileNames returns a QStringList, whereas PySide # returns a type (the first entry being the list of filenames). if isinstance(fileNames, types.TupleType): fileNames = fileNames[0] if hasattr(QtCore, 'QStringList') and isinstance( fileNames, QtCore.QStringList): fileNames = [str(i) for i in fileNames] if len(fileNames) > 0: for fileName in fileNames: if fileName != '': imgarr = np.array(Image.open(str(fileName))) imgarr = imgarr.swapaxes(0, 1) if imgarr.ndim == 2: imgarr = imgarr[:, ::-1] elif imgarr.ndim == 3: imgarr = imgarr[:, ::-1, :] newImages[fileName] = imgarr # Add filenames to list widget. Only add new filenames. If filename exists aready, then # it will not be added, but data will be updated for fileName in sorted(newImages.keys()): if not self.imageFiles.has_key(fileName): self.sidePanel.addImageToList(fileName) self.imageFiles[fileName] = newImages[fileName] # Show image in Main window self.vb.enableAutoRange() if self.sidePanel.imageFileList.currentRow() == -1: self.sidePanel.imageFileList.setCurrentRow(0) self.showImage( str(self.sidePanel.imageFileList.currentItem().text())) self.vb.disableAutoRange() def removeImage(self): """ Remove image from sidePanel imageFileList """ # Return if there is no image to remove if self.vb.img == None: return # Get current image in sidePanel imageFileList and remove from list currentRow = self.sidePanel.imageFileList.currentRow() image = self.sidePanel.imageFileList.takeItem(currentRow) imageName = str(image.text()) # Delete key and value from dictionary if imageName != '': del self.imageFiles[imageName] #self.imageFiles.pop(imageName,None) # Get image item in imageFileList to replace deleted image if self.sidePanel.imageFileList.count() == 0: self.vb.enableAutoRange() self.vb.removeItem(self.vb.img) self.vb.showImage(None) #self.vb.img = None self.vb.disableAutoRange() else: currentRow = self.sidePanel.imageFileList.currentRow() imageName = str( self.sidePanel.imageFileList.item(currentRow).text()) self.showImage(imageName) def showImage(self, imageFilename): """ Shows image in main view """ self.arr = self.imageFiles[imageFilename] self.vb.showImage(self.arr) def getImageToDisplay(self): """ Get current item in file list and display in main view""" try: imageFilename = str( self.sidePanel.imageFileList.currentItem().text()) except: pass else: self.showImage(imageFilename) def getBMD(self): """ Get change in BMD over time (e.g. for each image) for all ROIs. Revised function that converts the list of images into a 3D array and then uses the relative position of the ROIs to the current image, self.vb.img, to get the average BMD value e.g. it doesn't use setImage to change the image in the view. This requires that all images are the same size and in the same position. """ # Return if there is no image or rois in view if self.vb.img == None or len(self.vb.rois) == 0: return # Collect all images into a 3D array imageFilenames = self.sidePanel.getListOfImages() images = [self.imageFiles[str(name.text())] for name in imageFilenames] imageData = np.dstack(images) numImages = len(images) # Get BMD across image stack for each ROI numROIs = len(self.vb.rois) BMD = np.zeros((numImages, numROIs), dtype=float) self.roiNames = [] for i in xrange(numROIs): roi = self.vb.rois[i] self.roiNames.append(roi.name) arrRegion = roi.getArrayRegion(imageData, self.vb.img, axes=(0, 1)) avgROIvalue = arrRegion.mean(axis=0).mean(axis=0) BMD[:, i] = avgROIvalue # Calculate the BMD change (percentage of original) tol = 1.0e-06 for i in xrange(numROIs): if abs(BMD[0, i]) < tol: BMD[:, i] = 100. else: BMD[:, i] = BMD[:, i] / BMD[0, i] * 100. self.BMDchange = BMD - 100. if self.timeData == None or self.timeData.size != numImages: self.timeData = np.arange(numImages, dtype=float) # Plot results self.showResults() def imageAnalysis(self): # Generate images of BMD change if self.vb.img == None: return self.showImageWin() def sliderValueChanged(self, value): self.imageWin.sliderLabel.setText('BMD change: >= %d %s' % (value, '%')) self.setLookupTable(value) self.imageWin.vb.img2.setLookupTable(self.lut) def setLookupTable(self, val): lut = [] for i in range(256): if i > 127 + val: lut.append(matplotlib.cm.jet(255)) elif i < 127 - val: lut.append(matplotlib.cm.jet(0)) else: lut.append((0.0, 0.0, 0.0, 0.0)) lut = np.array(lut) * 255 self.lut = np.array(lut, dtype=np.ubyte) def createImageWin(self): self.buttMinimumSize = QtCore.QSize(70, 36) self.iconSize = QtCore.QSize(24, 24) if self.imageWin == None: self.imageWin = QtGui.QDialog(self, QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint | \ QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowMaximizeButtonHint) self.imageWin.setWindowTitle('BMDanalyse') self.imageWin.setWindowIcon(self.icons['BMDanalyseIcon']) self.imageWin.setMinimumSize(250, 500) self.imageWin.resize(self.imageWin.minimumSize()) # Create viewBox self.imageWin.glw = GraphicsLayoutWidget( ) # A GraphicsLayout within a GraphicsView self.imageWin.vb = ImageAnalysisViewBox(lockAspect=True, enableMenu=True) self.imageWin.vb.disableAutoRange() self.imageWin.glw.addItem(self.imageWin.vb) arr = self.imageFiles.values()[0] self.imageWin.vb.img1 = pg.ImageItem(arr, autoRange=False, autoLevels=False) self.imageWin.vb.addItem(self.imageWin.vb.img1) self.imageWin.vb.img2 = pg.ImageItem(None, autoRange=False, autoLevels=False) self.imageWin.vb.addItem(self.imageWin.vb.img2) self.imageWin.vb.autoRange() lut = [[int(255 * val) for val in matplotlib.cm.gray(i)[:3]] for i in xrange(256)] lut = np.array(lut, dtype=np.ubyte) self.imageWin.vb.img1.setLookupTable(lut) # Label to show index of current image label self.imageCurrCont = QtGui.QFrame() self.imageCurrCont.setLineWidth(2) self.imageCurrCont.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Raised) self.imageCurrCont.setMinimumWidth(70) self.imageWin.currLabel = QtGui.QLabel("") self.imageWin.currLabel.setAlignment(QtCore.Qt.AlignHCenter) imageCurrContLayout = QtGui.QHBoxLayout() imageCurrContLayout.addWidget(self.imageWin.currLabel) self.imageCurrCont.setLayout(imageCurrContLayout) # Create buttons to select images self.imageWin.buttCont = QtGui.QWidget() self.imageWin.buttPrev = QtGui.QPushButton( self.icons['imagePrevIcon'], "") self.imageWin.buttNext = QtGui.QPushButton( self.icons['imageNextIcon'], "") self.buttLayout = QtGui.QHBoxLayout() self.buttLayout.addStretch(1) self.buttLayout.addWidget(self.imageWin.buttPrev) self.buttLayout.addWidget(self.imageCurrCont) self.buttLayout.addWidget(self.imageWin.buttNext) self.buttLayout.addStretch(1) self.imageWin.buttCont.setLayout(self.buttLayout) self.imageWin.buttPrev.setMinimumSize(self.buttMinimumSize) self.imageWin.buttNext.setMinimumSize(self.buttMinimumSize) self.imageWin.buttPrev.setIconSize(self.iconSize) self.imageWin.buttNext.setIconSize(self.iconSize) self.buttLayout.setContentsMargins(0, 5, 0, 5) self.imageWin.buttPrev.clicked.connect(self.prevImage) self.imageWin.buttNext.clicked.connect(self.nextImage) # Create slider self.imageWin.sliderCon = QtGui.QWidget() self.imageWin.slider = QtGui.QSlider(self) self.imageWin.slider.setOrientation(QtCore.Qt.Horizontal) self.imageWin.slider.setMinimum(1) self.imageWin.slider.setMaximum(100) self.imageWin.slider.setMinimumWidth(100) self.imageWin.slider.valueChanged.connect(self.sliderValueChanged) self.imageWin.sliderLabel = QtGui.QLabel('1') self.imageWin.sliderLabel.setMinimumWidth(120) self.sliderLayout = QtGui.QHBoxLayout() self.sliderLayout.addStretch(1) self.sliderLayout.addWidget(self.imageWin.sliderLabel) self.sliderLayout.addWidget(self.imageWin.slider) self.sliderLayout.addStretch(1) self.imageWin.sliderCon.setLayout(self.sliderLayout) self.sliderLayout.setContentsMargins(0, 0, 0, 5) # Format image window self.imageWinLayout = QtGui.QVBoxLayout() self.imageWinLayout.addWidget(self.imageWin.glw) self.imageWinLayout.addWidget(self.imageWin.buttCont) self.imageWinLayout.addWidget(self.imageWin.sliderCon) self.imageWin.setLayout(self.imageWinLayout) self.imageWin.imagesRGB = None # Show self.imageWin.show() self.imageWin.slider.setValue(10) self.sliderValueChanged(10) self.imageWinIndex = 0 def prevImage(self): #numImages = len(self.imageFiles) minIndex = 0 currIndex = self.imageWinIndex prevIndex = currIndex - 1 self.imageWinIndex = max(prevIndex, minIndex) self.updateImageWin() def nextImage(self): numImages = len(self.imageFiles) maxIndex = numImages - 1 currIndex = self.imageWinIndex nextIndex = currIndex + 1 self.imageWinIndex = min(nextIndex, maxIndex) self.updateImageWin() def updateImageWin(self): imageFilenames = self.sidePanel.getListOfImages() imageName = imageFilenames[self.imageWinIndex] self.imageWin.vb.img1.setImage(self.imageFiles[str(imageName.text())], autoLevels=False) self.imageWin.vb.img2.setImage( self.imageWin.imagesRGB[self.imageWinIndex], autoLevels=False) self.imageWin.currLabel.setText( "%i / %i" % (self.imageWinIndex + 1, len(imageFilenames))) def showImageWin(self): self.createImageWin() #if self.imageWin.imagesRGB == None: self.imagesBMDpercentChange() self.imagesBMDpercentChange() self.updateImageWin() def imagesBMDpercentChange(self): # Get image arrays and convert to an array of floats imageFilenames = self.sidePanel.getListOfImages() images = [self.imageFiles[str(name.text())] for name in imageFilenames] imagesConv = [] for img in images: image = img.copy() image[np.where(image == 0)] = 1 image = image.astype(np.float) imagesConv.append(image) # Calculate percentage change and set with limits -100% to +100% imagesPercCh = [] imageInitial = imagesConv[0] for image in imagesConv: imagePercCh = (image - imageInitial) / imageInitial * 100. imagePercCh[np.where(imagePercCh > 100.)] = 100. imagePercCh[np.where(imagePercCh < -100.)] = -100. imagesPercCh.append(imagePercCh) numImages = len(imagesPercCh) self.imageWin.imagesRGB = [] for i in xrange(numImages): image = imagesPercCh[i] sx, sy = image.shape #imageCh = np.zeros((sx,sy),dtype=np.float) imageRGB = image * (255 / 200.) + (255 / 2.) self.imageWin.imagesRGB.append(imageRGB) def BMDtoCSVfile(self): """ Write BMD change to csv file """ fileName = QtGui.QFileDialog.getSaveFileName(None, self.tr("Export to CSV"), QtCore.QDir.currentPath(), self.tr("CSV (*.csv)")) # Fix for PyQt/PySide compatibility. PyQt returns a QString, whereas PySide returns a tuple (first entry is filename as string) if isinstance(fileName, types.TupleType): fileName = fileName[0] if hasattr(QtCore, 'QString') and isinstance(fileName, QtCore.QString): fileName = str(fileName) if not fileName == '': #if not fileName.isEmpty(): textFile = open(fileName, 'w') numFrames, numROIs = self.BMDchange.shape roiNames = self.roiNames header = "%10s," % 'Time' header += ((numROIs - 1) * '%10s,' + '%10s\n') % tuple(roiNames) textFile.write(header) for i in xrange(numFrames): textFile.write('%10.1f,' % self.timeData[i]) for j in xrange(numROIs): if j < numROIs - 1: fmt = '%10.3f,' else: fmt = '%10.3f\n' textFile.write(fmt % self.BMDchange[i, j]) textFile.close() def showResults(self, ): """ Plots BMD change using matplotlib """ # Create plot window if self.plotWin == None: self.plotWin = QtGui.QDialog(self, QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint | \ QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowMaximizeButtonHint) self.plotWin.setWindowTitle('BMDanalyse') self.plotWin.setWindowIcon(self.icons['BMDanalyseIcon']) self.plotWin.setMinimumSize(600, 500) self.plotWin.resize(self.minimumSize()) # Create Matplotlib widget self.mplw = MatplotlibWidget(size=(5, 6)) self.fig = self.mplw.getFigure() self.editDataButton = QtGui.QPushButton('Edit plot') self.exportCSVButton = QtGui.QPushButton('Export data') self.mplw.toolbar.addWidget(self.editDataButton) self.mplw.toolbar.addWidget(self.exportCSVButton) self.editDataButton.clicked.connect(self.showEditBox) self.exportCSVButton.clicked.connect(self.BMDtoCSVfile) # Format plot window self.plotWinLayout = QtGui.QVBoxLayout() self.plotWinLayout.addWidget(self.mplw) self.plotWin.setLayout(self.plotWinLayout) self.createFigure() self.plotWin.show() self.mplw.draw() def createFigure(self): """ Creates plot of results """ self.ax1 = self.fig.add_subplot(111) self.ax1.clear() self.fig.subplots_adjust(bottom=0.15, top=0.85, left=0.15, right=0.925) numFrames, numROIs = self.BMDchange.shape t = self.timeData # Plot data for i in xrange(numROIs): roiname = self.roiNames[i] self.ax1.plot(t, self.BMDchange[:, i], '-o', label=roiname, linewidth=2.0) kwargs = dict(y=1.05) # Or kwargs = {'y':1.05} self.ax1.set_title('Change in Bone Mineral Density over time', fontsize=14, fontweight='roman', **kwargs) self.ax1.set_xlabel('Time', fontsize=10) self.ax1.set_ylabel('Change in BMD (%)', fontsize=10) self.ax1.legend(loc=0) matplotlib.pyplot.setp(self.ax1.get_xmajorticklabels(), fontsize=10) matplotlib.pyplot.setp(self.ax1.get_ymajorticklabels(), fontsize=10) matplotlib.pyplot.setp(self.ax1.get_legend().get_texts(), fontsize=10) self.ax1.grid() def fillEditBox(self): rows, cols = self.BMDchange.shape for i in xrange(rows): itmValue = '%.2f' % self.timeData[i] itm = QtGui.QTableWidgetItem(itmValue) self.tableResults.setItem(i, 0, itm) for j in xrange(cols): itmValue = '%.2f' % self.BMDchange[i, j] itm = QtGui.QTableWidgetItem(itmValue) self.tableResults.setItem(i, j + 1, itm) def showEditBox(self): self.plotWin.editBox = QtGui.QDialog( self.plotWin, QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowTitleHint) self.plotWin.editBox.setWindowIcon(self.icons['BMDanalyseIcon']) self.plotWin.editBox.setWindowTitle('BMDanalyse') self.plotWin.editBox.setModal(True) # Add table layout = QtGui.QVBoxLayout() layout.setContentsMargins(10, 10, 10, 10) layout.setSpacing(20) rows, cols = self.BMDchange.shape self.tableResults = MyTableWidget(rows, cols + 1, self.plotWin.editBox) self.tableResults.verticalHeader().setVisible(True) # Set headers self.tableResults.setHorizontalHeaderItem( 0, QtGui.QTableWidgetItem('Time')) for i in xrange(cols): header = QtGui.QTableWidgetItem(self.roiNames[i]) self.tableResults.setHorizontalHeaderItem(i + 1, header) # Add values to table self.fillEditBox() # Set layout layout.addWidget(self.tableResults) self.buttonsFrame = QtGui.QFrame() self.buttonsLayout = QtGui.QHBoxLayout() self.buttonReset = QtGui.QPushButton('Reset') self.buttonSave = QtGui.QPushButton('Save') self.buttonClose = QtGui.QPushButton('Cancel') self.buttonReset.setFixedWidth(50) self.buttonSave.setFixedWidth(50) self.buttonClose.setFixedWidth(50) self.buttonClose.clicked.connect(self.plotWin.editBox.close) self.buttonSave.clicked.connect(self.updateTableValues) self.buttonReset.clicked.connect(self.fillEditBox) self.buttonsLayout.addStretch(1) self.buttonsLayout.addWidget(self.buttonReset) self.buttonsLayout.addWidget(self.buttonSave) self.buttonsLayout.addWidget(self.buttonClose) self.buttonsLayout.setContentsMargins(0, 0, 0, 0) self.buttonsFrame.setLayout(self.buttonsLayout) layout.addWidget(self.buttonsFrame) self.plotWin.editBox.setLayout(layout) self.plotWin.editBox.setMaximumSize(layout.sizeHint()) self.plotWin.editBox.show() def updateTableValues(self): # Create temporary arrays timeData = self.timeData.copy() BMDchange = self.BMDchange.copy() # Put the values from the tables into the temporary arrays rows = self.tableResults.rowCount() cols = self.tableResults.columnCount() for r in xrange(rows): for c in xrange(cols): item = self.tableResults.item(r, c) itemValue = float(item.text()) if c == 0: timeData[r] = itemValue else: BMDchange[r, c - 1] = itemValue # Check that time values are in increasing order. If so, then update arrays if any(np.diff(timeData) <= 0): self.errorMessage = QtGui.QMessageBox() self.errorMessage.setWindowIcon(self.icons['BMDanalyseIcon']) self.errorMessage.setWindowTitle('BMDanalyse') self.errorMessage.setText( 'Input error: Time values should be in order of increasing value' ) self.errorMessage.setIcon(QtGui.QMessageBox.Warning) self.errorMessage.open() else: self.timeData = timeData self.BMDchange = BMDchange self.createFigure() self.mplw.draw() self.plotWin.editBox.close()
class PlotW(object): def __init__(self, width, height, hAxisCtrl, vAxisCtrl): self.__window = GraphicsLayoutWidget() self.__window.resize(width, height) self.__window.move(0, 0) self.__window.setFocusPolicy(Qt.StrongFocus) self.__window.setObjectName("plotWindow") self.__window.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowMinimizeButtonHint) self.__window.show() plot = self.__window.addPlot(0, 0, 1, 1, enableMenu=False) self.__mainPlot = MainPlot(plot, hAxisCtrl, vAxisCtrl) waveLayout = self.__window.addLayout(0, 1, 1, 1) self.__wavePlots = WavePlots(waveLayout) self.__window.ci.layout.setColumnStretchFactor(0, 80) self.__window.ci.layout.setColumnStretchFactor(1, 20) def reset(self): self.__mainPlot.reset() self.__wavePlots.reset() def initialize(self, numChs): self.__wavePlots.initializePlots(numChs) def getWindow(self): return self.__window def setWindowTitle(self, title): self.__window.setWindowTitle(title) def getMainPlot(self): return self.__mainPlot def getWavePlots(self): return self.__wavePlots