def createImageGroupBox(self):
        self.imageForm = QGroupBox('Imaging')
        self.imageLayout = QGridLayout()

        ##raw image
        self.imv1 = RawImageWidget(scaled=True)
        ## tracking
        self.imv2 = RawImageWidget(scaled=True)
        ## mask
        self.imv3 = RawImageWidget(scaled=True)
        ## avergae
        self.imv4 = RawImageWidget(scaled=True)

        ## set background image
        self.imv1.setImage(self.bkImage)

        self.imageLayout.addWidget(QLabel("Raw:"), 0, 0, 1, 1)
        self.imageLayout.addWidget(QLabel("Detection:"), 0, 1, 1, 1)
        self.imageLayout.addWidget(self.imv1, 1, 0, 1, 1)
        self.imageLayout.addWidget(self.imv2, 1, 1, 1, 1)
        self.imageLayout.addWidget(QLabel("Mask:"), 2, 0, 1, 1)
        self.imageLayout.addWidget(QLabel("Moving average:"), 2, 1, 1, 1)
        self.imageLayout.addWidget(self.imv3, 3, 0, 1, 1)
        self.imageLayout.addWidget(self.imv4, 3, 1, 1, 1)

        self.imageForm.setLayout(self.imageLayout)
    def initialise_window(self):
        self.load_picture()
        self.app = QApplication([])
        self.win = MyQtWidget()

        #####################################
        ## Layout
        #####################################
        self.layout = QGridLayout()
        self.win.setLayout(self.layout)

        self.createRecordGroupBox()
        self.createDefaultGroupBox()
        self.createImageGroupBox()
        self.createSwitchFormGroupBox()
        self.createCalibrationFormGroupBox()
        self.createParamGroupBox()
        self.createPumpGroupBox()
        self.createTextGroupBox()
        self.resetPath()

        self.layout.addWidget(self.imageForm, 0, 0, 1, 3)

        self.layout.addWidget(self.textForm, 0, 4, 1, 3)

        self.layout.addWidget(self.paramForm, 2, 0, 1, 1)
        self.layout.addWidget(self.calibrationForm, 2, 1, 1, 1)
        self.layout.addWidget(self.pumpForm, 2, 2, 1, 1)

        self.layout.addWidget(self.switchForm, 3, 1, 1, 1)
        self.layout.addWidget(self.defaultForm, 3, 2, 1, 1)
        self.layout.addWidget(self.recordForm, 3, 0, 1, 1)

        self.win.show()
        return self.win
    def __init__(self, unfolding, parent=None):
        super(Window, self).__init__(parent)
        self.listCheckBox = []
        self.listLabel = []
        self.unfolding = unfolding

        for hinge in unfolding.all_hinges:
            self.listCheckBox.append(str(hinge))
            self.listLabel.append('')

        grid = QGridLayout()

        for i, v in enumerate(self.listCheckBox):
            self.listCheckBox[i] = QCheckBox(v)
            self.listLabel[i] = QLabel()
            grid.addWidget(self.listCheckBox[i], i, 0)
            grid.addWidget(self.listLabel[i], i, 1)
            if unfolding.all_hinges[i] in unfolding.open_hinges:
                self.listCheckBox[i].setChecked(True)
            else:
                self.listCheckBox[i].setChecked(False)

        self.button = QPushButton("Update hinges")
        self.button.clicked.connect(self.checkboxChanged)
        self.labelResult = QLabel()

        grid.addWidget(self.button, 10, 0, 1, 2)
        grid.addWidget(self.labelResult, 11, 0, 1, 2)
        self.setLayout(grid)
        self.setWindowTitle('Hinge Selection')
예제 #4
0
    def __init__(self, src, dest):
        super(CopyProgressPopup, self).__init__(self)
        self.src = src
        self.dest = dest
        self.numFiles = countFiles(src)
        self.thread = CopyThread(src, dest)

        self.progressbar = QProgressBar()
        self.progressbar.setMinimum(0)
        self.progressbar.setMaxiumum(self.numFiles)

        self.progresslabel = QLabel("0.0%")

        self.setWindowTitle("Copying to " + dest)

        self.layout = QGridLayout()
        layout.addWidget(self.progressbar, 0, 0)
        layout.addWidget(self.progresslabel, 0, 1)

        self.setLayout(layout)

        self.thread.partDone.connect(self.update)
        self.thread.procDone.connect(self.finish)

        self.show()
        self.thread.start()
    def __init__(self, parent=None):
        super().__init__()

        self.title = "Graphs and Stuff"
        self.width = 1200
        self.height = 900

        self.setWindowTitle(self.title)
        self.setGeometry(0, 0, self.width, self.height)

        self.layout = QGridLayout()
        self.layout.setContentsMargins(10, 10, 10, 10)
        self.layout_widget = QWidget()
        self.layout_widget.setLayout(self.layout)
        self.setCentralWidget(self.layout_widget)

        self.rewards_graph = utils.LiveGraph(title="Guard vs. Hostile",
                                             subgraph_count=2,
                                             sample_efficiency=0.05,
                                             parent=self)
        self.suffer_graph = utils.LiveGraph("Performance by Suffering", 1,
                                            self)
        self.ghost_graph = utils.LiveGraph("Performance by Ghosting", 1, self)
        self.exploration_graph = utils.LiveGraph(
            "Performance by Ghost Exploration", 1, self)

        self.layout.addWidget(self.rewards_graph.widget, 0, 0)
        self.layout.addWidget(self.exploration_graph.widget, 0, 1)
        self.layout.addWidget(self.suffer_graph.widget, 1, 0)
        self.layout.addWidget(self.ghost_graph.widget, 1, 1)

        # create testing chain
        self.tester = WorldTesterChain([
            WorldTester(config.set_suffering,
                        lambda p, r: self.suffer_graph.add_point(0, p, r), 0,
                        2, 20, config.SUFFERING),
            WorldTester(config.set_ghost_exploration,
                        lambda p, r: self.exploration_graph.add_point(0, p, r),
                        0, 0.1, 1, config.GHOST_EXPLORATION),
            WorldTester(config.set_ghost_count,
                        lambda p, r: self.ghost_graph.add_point(0, p, r), 0,
                        20, 200, config.GHOST_COUNT)
        ])

        # create pygame window
        self.pg_window = PygameWindow()

        #self.pg_window.run_world(self.tester.next_world(self))
        self.pg_window.run_world(World(self))

        self.show()

        self.is_closed = False

        # setup pygame update loop
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_pygame)
        self.timer.start(0)
    def __init__(self, scheme, parent):
        super(EditorSchemeDesigner, self).__init__(parent, Qt.Dialog)
        self.original_style = copy.copy(resources.CUSTOM_SCHEME)
        self._avoid_on_loading, self.saved, self._components = True, False, {}
        self.setWindowTitle(translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER)
        self.setMinimumSize(450, 480)
        self.setMaximumSize(500, 900)
        self.resize(450, 600)

        # all layouts and groupboxes
        group0 = QGroupBox(translations.TR_PROJECT_NAME)  # scheme filename
        group1 = QGroupBox(translations.TR_PROJECT_PROPERTIES)  # properties
        group2 = QGroupBox(translations.TR_PREVIEW)  # quick preview thingy
        group0_hbox, group1_vbox = QHBoxLayout(group0), QVBoxLayout(group1)
        this_dialog_vbox, group2_vbox = QVBoxLayout(self), QVBoxLayout(group2)
        self._grid, scrollArea, frame = QGridLayout(), QScrollArea(), QFrame()

        # widgets
        self.line_name, btnSave = QLineEdit(), QPushButton(
            translations.TR_SAVE)
        self.line_name.setPlaceholderText(getuser().capitalize() + "s_scheme")
        group0_hbox.addWidget(self.line_name)
        group0_hbox.addWidget(btnSave)
        self.connect(btnSave, SIGNAL("clicked()"), self.save_scheme)
        _demo = "<center>" + ascii_letters  # demo text for preview
        self.preview_label1, self.preview_label2 = QLabel(_demo), QLabel(_demo)
        group2_vbox.addWidget(self.preview_label1)
        group2_vbox.addWidget(self.preview_label2)

        # rows titles
        self._grid.addWidget(QLabel("<b>" + translations.TR_PROJECT_NAME), 0,
                             0)
        self._grid.addWidget(QLabel("<b>" + translations.TR_CODE), 0, 1)
        self._grid.addWidget(
            QLabel("<b>" + translations.TR_EDITOR_SCHEME_PICK_COLOR), 0, 2)

        # fill rows
        for key in sorted(tuple(resources.COLOR_SCHEME.keys())):
            self.add_item(key, scheme)
        self.preview_label1.setStyleSheet('background:transparent')
        self.preview_label2.setStyleSheet('color:     transparent')

        # fill the scroll area
        frame.setLayout(self._grid)
        scrollArea.setWidget(frame)
        group1_vbox.addWidget(scrollArea)

        # put groups on the dialog
        this_dialog_vbox.addWidget(group1)
        this_dialog_vbox.addWidget(group2)
        this_dialog_vbox.addWidget(group0)
        self._avoid_on_loading = self._modified = False
예제 #7
0
 def __init__(self, src, dest):
     super(CopyProgressPopup, self).__init__(self)
     self.src = src
     self.dest = dest
     self.numFiles = countFiles(src)
     self.thread = CopyThread(src, dest)
     
     self.progressbar = QProgressBar()
     self.progressbar.setMinimum(0)
     self.progressbar.setMaxiumum(self.numFiles)
     
     self.progresslabel = QLabel("0.0%")
     
     self.setWindowTitle("Copying to " + dest)
     
     self.layout = QGridLayout()
     layout.addWidget(self.progressbar, 0, 0)
     layout.addWidget(self.progresslabel, 0, 1)
     
     self.setLayout(layout)
     
     self.thread.partDone.connect(self.update)
     self.thread.procDone.connect(self.finish)
     
     self.show()
     self.thread.start()
예제 #8
0
 def __init__(self, modelRoot):
     super(NeuroKitVisualizer, self).__init__()
     layout = QGridLayout()
     self.toolbar = self.createToolbar()
     self.textEdit = self.createTextEdit()
     layout.addWidget(self.toolbar, 0, 0, 1, -1)
     layout.addWidget(self.textEdit, 1, 0, -1, -1)
예제 #9
0
    def __init__(self, parent, help):
        QDialog.__init__(self, parent)

        self.setWindowTitle(i18n("Package Manager Help"))
        self.resize(700, 500)
        self.setModal(True)

        self.layout = QGridLayout(self)
        self.htmlPart = QTextBrowser(self)
        self.layout.addWidget(self.htmlPart, 1, 1)

        locale = setSystemLocale(justGet=True)

        if locale in ["tr", "es", "en", "fr", "nl", "de", "sv"]:
            self.htmlPart.setSource(
                QUrl("/usr/share/package-manager/help/%s/%s" %
                     (locale, help_files[help])))

        else:
            self.htmlPart.setSource(
                QUrl("/usr/share/package-manager/help/en/%s" %
                     help_files[help]))
예제 #10
0
class HelpDialog(QDialog):
    def __init__(self, parent, help):
        QDialog.__init__(self, parent)

        self.setWindowTitle(i18n("Package Manager Help"))
        self.resize(700,500)
        self.setModal(True)

        self.layout = QGridLayout(self)
        self.htmlPart = QTextBrowser(self)
        self.layout.addWidget(self.htmlPart, 1, 1)

        locale = setSystemLocale(justGet = True)

        if locale in ["tr", "es", "en", "fr", "nl", "de", "sv"]:
            self.htmlPart.setSource(
                    QUrl("/usr/share/package-manager/help/%s/%s" %
                        (locale, help_files[help])))

        else:
            self.htmlPart.setSource(
                    QUrl("/usr/share/package-manager/help/en/%s" %
                        help_files[help]))
예제 #11
0
class CopyProgressPopup(QWidget):
    def __init__(self, src, dest):
        super(CopyProgressPopup, self).__init__(self)
        self.src = src
        self.dest = dest
        self.numFiles = countFiles(src)
        self.thread = CopyThread(src, dest)
        
        self.progressbar = QProgressBar()
        self.progressbar.setMinimum(0)
        self.progressbar.setMaxiumum(self.numFiles)
        
        self.progresslabel = QLabel("0.0%")
        
        self.setWindowTitle("Copying to " + dest)
        
        self.layout = QGridLayout()
        layout.addWidget(self.progressbar, 0, 0)
        layout.addWidget(self.progresslabel, 0, 1)
        
        self.setLayout(layout)
        
        self.thread.partDone.connect(self.update)
        self.thread.procDone.connect(self.finish)
        
        self.show()
        self.thread.start()
        
    def update(self, val):
        self.progressbar.setValue(val/self.numFiles)
        perct = "{0}%".format(val/self.numFiles)
        self.nameLabel.setText(perct)
        
    def finish(self):
        self.layout.removeWidget(self.progressbar)
        self.layout.removeWidget(self.progresslabel)
        self.progressbar.deleteLater()
        self.progresslable.deleteLater()
        statuslabel = QLabel("Copy Finished")
        okayBut = QPushButton("Okay")
        self.layout.addWidget(statuslabel, 0, 0)
        self.layout.addWidget(okayBut, 1, 0)
        okayBut.clicked.connect(close(self))
예제 #12
0
class CopyProgressPopup(QWidget):
    def __init__(self, src, dest):
        super(CopyProgressPopup, self).__init__(self)
        self.src = src
        self.dest = dest
        self.numFiles = countFiles(src)
        self.thread = CopyThread(src, dest)

        self.progressbar = QProgressBar()
        self.progressbar.setMinimum(0)
        self.progressbar.setMaxiumum(self.numFiles)

        self.progresslabel = QLabel("0.0%")

        self.setWindowTitle("Copying to " + dest)

        self.layout = QGridLayout()
        layout.addWidget(self.progressbar, 0, 0)
        layout.addWidget(self.progresslabel, 0, 1)

        self.setLayout(layout)

        self.thread.partDone.connect(self.update)
        self.thread.procDone.connect(self.finish)

        self.show()
        self.thread.start()

    def update(self, val):
        self.progressbar.setValue(val / self.numFiles)
        perct = "{0}%".format(val / self.numFiles)
        self.nameLabel.setText(perct)

    def finish(self):
        self.layout.removeWidget(self.progressbar)
        self.layout.removeWidget(self.progresslabel)
        self.progressbar.deleteLater()
        self.progresslable.deleteLater()
        statuslabel = QLabel("Copy Finished")
        okayBut = QPushButton("Okay")
        self.layout.addWidget(statuslabel, 0, 0)
        self.layout.addWidget(okayBut, 1, 0)
        okayBut.clicked.connect(close(self))
예제 #13
0
    def initUI(self):

        grid = QGridLayout()
        self.vtkWidget = QVTKRenderWindowInteractor(self)
        grid.addWidget(self.vtkWidget, 0, 0, 1, 1)

        btn_close = QPushButton("close", self)
        btn_close.clicked.connect(self.close)
        grid.addWidget(btn_close, 1, 0, 1, 1)

        self.setLayout(grid)
        self.setWindowTitle('VTK Viewer')
        self.show()
예제 #14
0
 def setup(self):
     #hRangeBox=QHBoxLayout()
     hRangeGrid=QGridLayout()
     
     self.labelXmin=QLabel('Xmin:')
     self.xMinBox=QDoubleSpinBox(self)
     self.xMinBox.setMinimum(-100000)
     self.xMinBox.setMaximum(100000)
     hRangeGrid.addWidget(self.labelXmin,0,0)
     hRangeGrid.addWidget(self.xMinBox,0,1)
     self.labelXmax=QLabel('Xmax:')
     self.xMaxBox=QDoubleSpinBox(self)
     self.xMaxBox.setMaximum(100000)
     self.xMaxBox.setMinimum(-100000)
     hRangeGrid.addWidget(self.labelXmax,1,0)
     hRangeGrid.addWidget(self.xMaxBox,1,1)
     
     self.labelYmin=QLabel('Ymin:')
     self.yMinBox=QDoubleSpinBox(self)
     self.yMinBox.setMinimum(-100000)
     self.yMinBox.setMaximum(100000)
     hRangeGrid.addWidget(self.labelYmin,2,0)
     hRangeGrid.addWidget(self.yMinBox,2,1)
     self.labelYmax=QLabel('Ymax:')
     self.yMaxBox=QDoubleSpinBox(self)
     self.yMaxBox.setMaximum(100000)
     self.yMaxBox.setMinimum(-100000)
     hRangeGrid.addWidget(self.labelYmax,3,0)
     hRangeGrid.addWidget(self.yMaxBox,3,1)
     self.applyButton=QPushButton('Apply')
     self.ResetButton=QPushButton('Reset')
     hRangeGrid.addWidget(self.applyButton,4,0)
     hRangeGrid.addWidget(self.ResetButton,4,1)
     self.setLayout(hRangeGrid)
예제 #15
0
파일: dictGUI.py 프로젝트: mjirik/lisa
    def __init__(self, config_in, ncols=2):
        super(DictGui, self).__init__()

        self.setWindowTitle('Lisa Config')
        self.config = ConfigManager()
        self.ncols = ncols
# used with other module. If it is set, lisa config is deleted
        self.reset_config = False

        CHOICE_A = "{pairwise_alpha_per_mm2: 45, return_only_object_with_seeds: true}"
        # CHOICE_A = 23

        CHOICE_B = 2
        CHOICE_C = 3
        CHOICE_D = 4

        map_dict = {
            'Graph-Cut': CHOICE_A,
            'Choice B': CHOICE_B,
            'Choice C': CHOICE_C,
            'Choice D': CHOICE_D,
        }
        config_def = {
            'working_voxelsize_mm': 2.0,
            'save_filetype': 'pklz',
            # 'manualroi': True,
            'segparams': CHOICE_A,
        }
        
        config_def.update(config_in)
        
        self.config.set_defaults(config_def)

        gd = QGridLayout()
        gd_max_i = 0
        for key, value in config_in.items():
            if type(value) is int:
                sb = QSpinBox()
                sb.setRange(-100000, 100000)
            elif type(value) is float:
                sb = QDoubleSpinBox()
            elif type(value) is str:
                sb = QLineEdit()
            elif type(value) is bool:
                sb = QCheckBox()
            else:
                logger.error("Unexpected type in config dictionary")

            row = gd_max_i / self.ncols
            col = (gd_max_i % self.ncols) * 2

            gd.addWidget(QLabel(key),row, col +1) 
            gd.addWidget(sb, row, col + 2)
            self.config.add_handler(key, sb)
            gd_max_i += 1




        # gd.addWidget(QLabel("save filetype"), 1, 1)
        # te = QLineEdit()
        # gd.addWidget(te, 1, 2)
        # self.config.add_handler('save_filetype', te)
        #
        # gd.addWidget(QLabel("segmentation parameters"), 2, 1)
        # te = QLineEdit()
        # gd.addWidget(te, 2, 2)
        # self.config.add_handler('segparams', te)

        # cb = QCheckBox()
        # gd.addWidget(cb, 2, 2)
        # self.config.add_handler('active', cb)

        # gd.addWidget(QLabel("segmentation parameters"), 3, 1)
        # cmb = QComboBox()
        # cmb.addItems(map_dict.keys())
        # gd.addWidget(cmb, 3, 2)
        # self.config.add_handler('segparams', cmb, mapper=map_dict)

        self.current_config_output = QTextEdit()
        # rid.setColumnMinimumWidth(3, logo.width()/2)
        text_col = (self.ncols * 2) + 3
        gd.setColumnMinimumWidth(text_col, 500)
        gd.addWidget(self.current_config_output, 1, text_col, (gd_max_i/2)-1, 1)

        btn_reset_config = QPushButton("Default", self)
        btn_reset_config.clicked.connect(self.btnResetConfig)
        gd.addWidget(btn_reset_config, 0, text_col)

        btn_save_config = QPushButton("Ok", self)
        btn_save_config.clicked.connect(self.btnSaveConfig)
        gd.addWidget(btn_save_config, (gd_max_i / 2), text_col)

        self.config.updated.connect(self.show_config)

        self.show_config()

        # my line
        self.setLayout(gd)
예제 #16
0
#!/usr/bin/env python3

# FinPlot: https://github.com/highfestiva/finplot
# https://doc.qt.io/qt-5/qgridlayout.html#details
import finplot as fplt
from functools import lru_cache
from PyQt5.QtWidgets import QGraphicsView, QComboBox, QLabel
from PyQt5.QtGui import QApplication, QGridLayout
from threading import Thread
import yfinance as yf

# Setup layout
app = QApplication([])
win = QGraphicsView()
win.setWindowTitle('TradingView wannabe')
layout = QGridLayout()
win.setLayout(layout)
win.showMaximized()

combo = QComboBox()
combo.setEditable(True)
[
    combo.addItem(i)
    for i in 'SPY ^AXJO GC=F GLD ^TNX BTC-USD ETH-USD XRP-USD'.split()
]
layout.addWidget(combo, 0, 0, 1, 1)
info = QLabel()
layout.addWidget(info, 0, 1, 1, 1)

ax = fplt.create_plot(init_zoom_periods=100)
cross_hair_color = '#000000'
예제 #17
0
파일: mshow.py 프로젝트: lycying/seeking
 def invoke(self):
     searchInput = QLineEdit()
     normalInput = QPlainTextEdit()
     normalInput.setMaximumHeight(100)
     searchBtn = QPushButton("Search")
     sayBtn = QPushButton("Hmm..")
     
     
     listTops = QWidget()
     
     layoutWidget = QGridLayout()
     layoutWidget.addWidget(searchInput,1,0)
     layoutWidget.addWidget(searchBtn,1,1)
     layoutWidget.addWidget(normalInput,2,0)
     layoutWidget.addWidget(sayBtn,2,1)
     layoutWidget.addWidget(listTops,3,0,8,1)
     
     self.setLayout(layoutWidget)
    def __init__(self, parent):
        super(EditorCompletion, self).__init__()
        self._preferences = parent
        vbox = QVBoxLayout(self)

        groupBoxClose = QGroupBox(translations.TR_PREF_EDITOR_COMPLETE)
        formClose = QGridLayout(groupBoxClose)
        formClose.setContentsMargins(5, 15, 5, 5)
        self._checkParentheses = QCheckBox(
            translations.TR_PREF_EDITOR_PARENTHESES + " ()")
        self._checkParentheses.setChecked('(' in settings.BRACES)
        self._checkKeys = QCheckBox(translations.TR_PREF_EDITOR_KEYS + " {}")
        self._checkKeys.setChecked('{' in settings.BRACES)
        self._checkBrackets = QCheckBox(translations.TR_PREF_EDITOR_BRACKETS +
                                        " []")
        self._checkBrackets.setChecked('[' in settings.BRACES)
        self._checkSimpleQuotes = QCheckBox(
            translations.TR_PREF_EDITOR_SIMPLE_QUOTES)
        self._checkSimpleQuotes.setChecked("'" in settings.QUOTES)
        self._checkDoubleQuotes = QCheckBox(
            translations.TR_PREF_EDITOR_DOUBLE_QUOTES)
        self._checkDoubleQuotes.setChecked('"' in settings.QUOTES)
        self._checkCompleteDeclarations = QCheckBox(
            translations.TR_PREF_EDITOR_COMPLETE_DECLARATIONS.format(
                resources.get_shortcut("Complete-Declarations").toString(
                    QKeySequence.NativeText)))
        self._checkCompleteDeclarations.setChecked(
            settings.COMPLETE_DECLARATIONS)
        formClose.addWidget(self._checkParentheses,
                            1,
                            1,
                            alignment=Qt.AlignTop)
        formClose.addWidget(self._checkKeys, 1, 2, alignment=Qt.AlignTop)
        formClose.addWidget(self._checkBrackets, 2, 1, alignment=Qt.AlignTop)
        formClose.addWidget(self._checkSimpleQuotes,
                            2,
                            2,
                            alignment=Qt.AlignTop)
        formClose.addWidget(self._checkDoubleQuotes,
                            3,
                            1,
                            alignment=Qt.AlignTop)
        vbox.addWidget(groupBoxClose)

        groupBoxCode = QGroupBox(translations.TR_PREF_EDITOR_CODE_COMPLETION)
        formCode = QGridLayout(groupBoxCode)
        formCode.setContentsMargins(5, 15, 5, 5)
        self._checkCodeDot = QCheckBox(
            translations.TR_PREF_EDITOR_ACTIVATE_COMPLETION)
        self._checkCodeDot.setChecked(settings.CODE_COMPLETION)
        formCode.addWidget(self._checkCompleteDeclarations,
                           5,
                           1,
                           alignment=Qt.AlignTop)

        formCode.addWidget(self._checkCodeDot, 6, 1, alignment=Qt.AlignTop)
        vbox.addWidget(groupBoxCode)
        vbox.addItem(
            QSpacerItem(0, 10, QSizePolicy.Expanding, QSizePolicy.Expanding))

        self.connect(self._preferences, SIGNAL("savePreferences()"), self.save)
class MyLiveTracker(object):
    def __init__(self, opt=1):

        ##########################
        ##### default saving directory
        ##########################
        self.default_path = '/Users/virginiarutten/Documents/deep_fish/videos'
        self.filename = 'test'
        self.ext = '.avi'

        self.dt = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")[2:]
        self.foldername = self.default_path + '/' + self.dt[:6]
        self.path = self.get_path()
        self.check_dir()

        self.save = False
        self.cameraPort = 1

        self.recording = False
        self.trialOn = False
        self.flowOn = False
        self.ARD = False

        self.trialTime = 10
        self.trialSleepTime = 10

        ##########################
        ##### Arduino settings
        ##########################
        self.flowOffDelay = 1
        self.flowOnDelay = 1

        self.imW = int(640 / 2)
        self.imH = int(360 / 2)
        self.imfps = 25

        self.trialTimer = MyTimer()
        self.trialTimer.restart()

        self.ite = 0

        self.args = self.initialise_tracking_variables()
        self.win = self.initialise_window()
        self.recorder = self.initialise_videorecorder()
        self.Tracker = self.initialise_tracker()

        ##########################
        ##### Arduino
        ##########################
        self.ARDPort = self.ArdPortComboBox.currentData()
        self.Ard = self.initialise_Ard()

        ##########################
        ##### Threads
        ##########################
        self.recordingThread = MyThread(self.start_recording)
        self.recordingThread.start()
        self.trialThread = MyThread(self.start_trial)
        self.trialThread.start()

        self.recording = True

    def check_dir(self):
        ''' check that directory of the day exisits
        and that filename is unique'''
        if not os.path.isdir(self.foldername):
            print('creating directory...')
            os.mkdir(self.foldername)
        file_num = 1
        while os.path.exists(self.path):
            print('file already exisits...\nrenaming')
            print(self.path)
            self.filename = self.filename + str(file_num)
            file_num += 1
            self.path = self.get_path()

    def initialise_tracker(self):
        self.Tracker = MyRealTimeTracker(self.args)
        return self.Tracker

    def initialise_tracking_variables(self):
        ''' default values '''

        self.keypoints = {}
        self.mvAvgFrame = None
        self.fishNum = 4
        self.area_mn = 35
        ## threshold mask value
        self.pVal = 180
        self.pVal_mx = 255
        self.text = None

        self.pre_frames = 5

        self.args = {}
        self.args['pVal'] = self.pVal
        self.args['pVal_mx'] = self.pVal_mx
        self.args['fishNum'] = self.fishNum
        self.args['area_mn'] = self.area_mn
        self.args['keypoints'] = self.keypoints
        self.args['pre_frames'] = self.pre_frames
        return self.args

    def get_path(self):
        return self.foldername + '/' + self.dt + self.filename + self.ext

    def initialise_videorecorder(self):
        ''' initialises recorder'''
        self.num_saved_frame = 0
        self.cameraPort = self.cameraComboBox.currentIndex()
        self.check_dir()
        if self.path[-3:] != 'avi':
            print('please check extension')

        print('initialising recording...\noutput file:{0}'.\
             format(self.path))

        self.recorder = MyVideoRecorder(cameraport = self.cameraPort,\
                                        path = self.path,\
                                        imH = self.imH,\
                                        imW = self.imW,\
                                       fps = self.imfps)

        wasrecording = False
        if self.recording:
            wasrecording = True
            self.recording = False

        self.recorder.initialise_camera()  ### reinitialise camera
        self.camera = self.recorder.camera  ### test camera works
        if self.camera.grab() == False:
            if self.cameraPort == 1:
                self.cameraPort = 0
                self.cameraComboBox.setCurrentIndex(self.cameraPort)
                print('no camera detected... camera changed')
        if wasrecording:
            self.recording = True
        else:
            self.recording = False
            wasrecording = False

        return self.recorder

    def initialise_Ard(self):
        try:
            self.Ard = MyArduino()
            self.ARDport = self.Ard.port
            self.ARD = True
        except:
            print('no valid port found \nplease check')
            self.ARD = False
        return self.Ard

    def load_picture(self):
        file_path = '/Users/virginiarutten/Documents/deep_fish/assets/pavlov_dog.jpg'
        self.bkImage = np.array(Image.open(file_path)).T

    def initialise_window(self):
        self.load_picture()
        self.app = QApplication([])
        self.win = MyQtWidget()

        #####################################
        ## Layout
        #####################################
        self.layout = QGridLayout()
        self.win.setLayout(self.layout)

        self.createRecordGroupBox()
        self.createDefaultGroupBox()
        self.createImageGroupBox()
        self.createSwitchFormGroupBox()
        self.createCalibrationFormGroupBox()
        self.createParamGroupBox()
        self.createPumpGroupBox()
        self.createTextGroupBox()
        self.resetPath()

        self.layout.addWidget(self.imageForm, 0, 0, 1, 3)

        self.layout.addWidget(self.textForm, 0, 4, 1, 3)

        self.layout.addWidget(self.paramForm, 2, 0, 1, 1)
        self.layout.addWidget(self.calibrationForm, 2, 1, 1, 1)
        self.layout.addWidget(self.pumpForm, 2, 2, 1, 1)

        self.layout.addWidget(self.switchForm, 3, 1, 1, 1)
        self.layout.addWidget(self.defaultForm, 3, 2, 1, 1)
        self.layout.addWidget(self.recordForm, 3, 0, 1, 1)

        self.win.show()
        return self.win

    def createImageGroupBox(self):
        self.imageForm = QGroupBox('Imaging')
        self.imageLayout = QGridLayout()

        ##raw image
        self.imv1 = RawImageWidget(scaled=True)
        ## tracking
        self.imv2 = RawImageWidget(scaled=True)
        ## mask
        self.imv3 = RawImageWidget(scaled=True)
        ## avergae
        self.imv4 = RawImageWidget(scaled=True)

        ## set background image
        self.imv1.setImage(self.bkImage)

        self.imageLayout.addWidget(QLabel("Raw:"), 0, 0, 1, 1)
        self.imageLayout.addWidget(QLabel("Detection:"), 0, 1, 1, 1)
        self.imageLayout.addWidget(self.imv1, 1, 0, 1, 1)
        self.imageLayout.addWidget(self.imv2, 1, 1, 1, 1)
        self.imageLayout.addWidget(QLabel("Mask:"), 2, 0, 1, 1)
        self.imageLayout.addWidget(QLabel("Moving average:"), 2, 1, 1, 1)
        self.imageLayout.addWidget(self.imv3, 3, 0, 1, 1)
        self.imageLayout.addWidget(self.imv4, 3, 1, 1, 1)

        self.imageForm.setLayout(self.imageLayout)

    def createTextGroupBox(self):
        self.textForm = QGroupBox('Imaging')
        self.textLayout = QFormLayout()

        ## parameters
        self.maxArea_box = QtGui.QLineEdit()
        self.num_detected_box = QtGui.QLineEdit()
        self.maxArea_box.setText('0')
        self.num_detected_box.setText('0')

        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(QLabel("max area:"))
        hbox.addWidget(self.maxArea_box)
        hboxD = QtGui.QHBoxLayout()
        hboxD.addWidget(QLabel("fish #:"))
        hboxD.addWidget(self.num_detected_box)

        self.textLayout.addRow(hbox)
        self.textLayout.addRow(hboxD)

        self.textForm.setLayout(self.textLayout)

    def createSwitchFormGroupBox(self):
        self.switchForm = QGroupBox("Controller")
        self.switchLayout = QFormLayout()

        ######################
        #### Trial/Lights
        #####################

        self.lightOn_btn = QtGui.QPushButton('Light On', self.win)
        self.lightOn_btn.clicked.connect(self.on_lightOn)

        self.lightOff_btn = QtGui.QPushButton('Light Off', self.win)
        self.lightOff_btn.clicked.connect(self.on_lightOff)

        self.trialOn_btn = QtGui.QPushButton('Start Trial', self.win)
        self.trialOn_btn.clicked.connect(self.on_trialOn)

        self.trialOff_btn = QtGui.QPushButton('Stop Trial', self.win)
        self.trialOff_btn.clicked.connect(self.on_trialOff)
        self.switchLayout.addRow(self.lightOn_btn, self.lightOff_btn)
        self.switchLayout.addRow(self.trialOn_btn, self.trialOff_btn)

        self.switchForm.setLayout(self.switchLayout)

    def createCalibrationFormGroupBox(self):
        self.calibrationForm = QGroupBox("Image Calibration")
        self.calibrationLayout = QFormLayout()

        self.slider = QSlider(Qt.Horizontal)
        self.slider.setMinimum(0)
        self.slider.setMaximum(255)
        self.slider.setValue(self.pVal)
        self.slider.setTickPosition(QSlider.TicksBelow)
        self.slider.setTickInterval(10)
        self.slider.valueChanged.connect(self.on_slidervaluechange)
        self.textSlider = QtGui.QLineEdit(str(self.pVal))

        hbox_mn = QtGui.QHBoxLayout()
        hbox_mn.addWidget(self.slider)
        hbox_mn.addWidget(self.textSlider)

        self.slider2 = QSlider(Qt.Horizontal)
        self.slider2.setMinimum(0)
        self.slider2.setMaximum(255)
        self.slider2.setValue(self.pVal_mx)
        self.slider2.setTickPosition(QSlider.TicksBelow)
        self.slider2.setTickInterval(10)
        self.slider2.valueChanged.connect(self.on_slider2valuechange)
        self.textSlider2 = QtGui.QLineEdit(str(self.pVal_mx), self.win)

        hbox_mx = QtGui.QHBoxLayout()
        hbox_mx.addWidget(self.slider2)
        hbox_mx.addWidget(self.textSlider2)

        self.ROIslider = QSlider(Qt.Horizontal)
        self.ROIslider.setMinimum(0)
        self.ROIslider.setMaximum(1000)
        self.ROIslider.setValue(self.area_mn)
        self.ROIslider.setTickPosition(QSlider.TicksBelow)
        self.ROIslider.setTickInterval(100)
        self.ROIslider.valueChanged.connect(self.on_ROIslidervaluechange)
        self.ROItextSlider = QLineEdit(str(self.area_mn))

        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(self.ROIslider)
        hbox.addWidget(self.ROItextSlider)

        self.calibrationLayout.addRow(QLabel("ROI max area:"), hbox)
        self.calibrationLayout.addRow(QLabel("px min:"), hbox_mn)
        self.calibrationLayout.addRow(QLabel("px max:"), hbox_mx)

        self.calibrationForm.setLayout(self.calibrationLayout)

    def createPumpGroupBox(self):
        self.pumpForm = QGroupBox("Pump settings")
        self.pumpFormLayout = QFormLayout()

        self.flowOff1_btn = QtGui.QPushButton('Increase')
        self.flowOff0_btn = QtGui.QPushButton('Decrease')

        self.flowOn1_btn = QtGui.QPushButton('Increase')
        self.flowOn0_btn = QtGui.QPushButton('Decrease')

        self.flowOn1_btn.clicked.connect(self.on_flowOn1)
        self.flowOn0_btn.clicked.connect(self.on_flowOn0)
        self.flowOff1_btn.clicked.connect(self.on_flowOff1)
        self.flowOff0_btn.clicked.connect(self.on_flowOff0)

        self.ardReset_btn = QtGui.QPushButton('reset flow')
        self.ardReset_btn.clicked.connect(self.on_ARDreset)

        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(self.flowOn0_btn)
        hbox.addWidget(self.flowOn1_btn)

        hboxOff = QtGui.QHBoxLayout()
        hboxOff.addWidget(self.flowOff0_btn)
        hboxOff.addWidget(self.flowOff1_btn)

        self.pumpFormLayout.addRow(QLabel("On time:"), hbox)
        self.pumpFormLayout.addRow(QLabel("Off time:"), hboxOff)
        self.pumpFormLayout.addRow(self.ardReset_btn)
        self.pumpForm.setLayout(self.pumpFormLayout)

    def createParamGroupBox(self):
        self.paramForm = QGroupBox("Trial parameters")
        self.paramFormLayout = QFormLayout()

        self.Timer_tbox = QtGui.QLineEdit()

        self.trialTime_tbox = QtGui.QLineEdit()
        self.trialTime_tbox.textChanged.connect(self.on_trialTime_changed)
        self.trialSleepTime_tbox = QtGui.QLineEdit()
        self.trialSleepTime_tbox.textChanged.connect(
            self.on_trialSleepTime_changed)
        self.trialTime_tbox.setText(str(self.trialTime))
        self.trialSleepTime_tbox.setText(str(self.trialSleepTime))
        self.Timer_tbox.setText(str(0))

        self.paramFormLayout.addRow(QLabel("Trial time:"), self.trialTime_tbox)
        self.paramFormLayout.addRow(QLabel("Stimulus time:"),
                                    self.trialSleepTime_tbox)

        self.paramFormLayout.addRow(QLabel("Time left:"), self.Timer_tbox)

        self.paramFormLayout.addRow(QLabel("Time:"), QSpinBox())
        self.paramForm.setLayout(self.paramFormLayout)

    def createDefaultGroupBox(self):
        self.defaultForm = QtGui.QGroupBox("Video capture")
        self.defaultFormLayout = QFormLayout()

        self.ArdPortComboBox = QComboBox()
        self.ArdPortComboBox.addItem("Port 14511", '/dev/cu.usbmodem14511')
        self.ArdPortComboBox.addItem("Port 14311", '/dev/cu.usbmodem14311')
        self.ArdPortComboBox.addItem("Port 1461", '/dev/cu.usbmodem1461')
        self.ArdPortComboBox.currentIndexChanged.connect(self.on_setARDport)

        self.cameraComboBox = QComboBox()
        self.cameraComboBox.addItem("0", '0')
        self.cameraComboBox.addItem("1", '1')
        self.cameraComboBox.currentIndexChanged.connect(self.on_setcameraport)

        self.start_btn = QtGui.QPushButton('start')
        self.start_btn.clicked.connect(self.on_start)

        ## stop flow button
        self.stop_btn = QtGui.QPushButton('stop')
        self.stop_btn.clicked.connect(self.on_stop)

        ## quit app button
        self.qbtn = QtGui.QPushButton('exit')
        self.qbtn.clicked.connect(self.on_quit)
        self.qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)

        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(self.start_btn)
        hbox.addWidget(self.stop_btn)
        hbox.addWidget(self.qbtn)

        self.defaultFormLayout.addRow(hbox)

        self.defaultFormLayout.addRow(QLabel("Arduino Port:"),\
                                     self.ArdPortComboBox)

        self.defaultFormLayout.addRow(QLabel("camera:"),\
                                     self.cameraComboBox)

        self.defaultForm.setLayout(self.defaultFormLayout)

    def createRecordGroupBox(self):
        self.recordForm = QtGui.QGroupBox("Video capture")
        self.recordFormLayout = QFormLayout()

        self.path_bx = QtGui.QLineEdit()
        self.resetPath()

        self.file_btn = QtGui.QPushButton("save to")
        self.file_btn.clicked.connect(self.on_getfile)

        self.file_bx = QtGui.QLineEdit()
        self.file_bx.textChanged.connect(self.on_fileChange)
        self.file_bx.setText(self.filename)

        self.save_btn = QtGui.QCheckBox()
        self.save_btn.setChecked(self.save)
        self.save_btn.stateChanged.connect(self.on_saveClick)

        hbox = QtGui.QHBoxLayout()
        self.recordFormLayout.addRow(self.file_btn, self.file_bx)
        self.recordFormLayout.addRow(QLabel("path:"), self.path_bx)
        self.recordFormLayout.addRow(QLabel("save:"), self.save_btn)

        self.recordForm.setLayout(self.recordFormLayout)

    #################
    ### slots
    ################

    @pyqtSlot()
    def on_getfile(self):
        self.foldername = QtGui.QFileDialog.getExistingDirectory()
        self.resetPath()

    @pyqtSlot()
    def on_fileChange(self):
        self.filename = self.file_bx.text()
        self.resetPath()

    @pyqtSlot()
    def on_setcameraport(self):
        self.initialise_videorecorder()

    @pyqtSlot()
    def on_trialTime_changed(self):
        try:
            self.trialTime = int(self.trialTime_tbox.text())

        except:
            self.trialTime_tbox.setText(str(1))
            print('only integrs valid')

    @pyqtSlot()
    def on_trialSleepTime_changed(self):
        try:
            self.trialSleepTime = int(self.trialSleepTime_tbox.text())
        except:
            self.trialSleepTime_tbox.setText(str(1))
            print('only integrs valid')

    @pyqtSlot()
    def on_setARDport(self):
        pass

    #  if self.ARD:
    #      self.ARDPort = self.ArdPortComboBox.currentData()
    #      print('ARD port set to ={0}'.format(self.ARDPort))
    #  else:
    #      print('no ARD detected')

    @pyqtSlot()
    def on_trialOn(self):
        print('trial starting')
        self.flowOn = False
        self.resetARD()
        self.trialTimer.restart()
        self.trialOn = True

    @pyqtSlot()
    def on_trialOff(self):
        print('trial ended')
        self.trialTimer.restart()
        self.trialOn = False
        self.flowOn = False
        self.resetARD()

    @pyqtSlot()
    def on_ARDreset(self):
        print('resetting ARD')
        self.resetFlowRate()

    @pyqtSlot()
    def on_flowOn1(self):
        print('changing flow rate')
        try:
            self.Ard.sendChar('u')
            self.resetARD()
        except:
            pass

    @pyqtSlot()
    def on_flowOn0(self):
        print('changing flow rate')
        try:
            self.Ard.sendChar('d')
            self.resetARD()
        except:
            pass

    @pyqtSlot()
    def on_flowOff1(self):
        print('changing flow rate')
        try:
            self.Ard.sendChar('k')
            self.resetARD()
        except:
            pass

    @pyqtSlot()
    def on_flowOff0(self):
        print('changing flow rate')
        try:
            self.Ard.sendChar('j')
            self.resetARD()
        except:
            pass

    @pyqtSlot()
    def on_lightOn(self):
        self.flowOn = True
        self.resetARD()

    @pyqtSlot()
    def on_lightOff(self):
        self.flowOn = False
        self.resetARD()

    @pyqtSlot()
    def on_slidervaluechange(self):
        self.pVal = int(self.slider.value())
        self.Tracker.pVal = self.pVal
        self.textSlider.setText(str(self.pVal))

    @pyqtSlot()
    def on_slider2valuechange(self):
        self.pVal_mx = int(self.slider2.value())
        self.Tracker.pVal_mx = self.pVal_mx
        self.textSlider2.setText(str(self.pVal_mx))

    @pyqtSlot()
    def on_ROIslidervaluechange(self):
        self.area_mn = int(self.ROIslider.value())
        self.Tracker.area_mn = self.area_mn
        self.ROItextSlider.setText(str(self.area_mn))

    @pyqtSlot()
    def on_start(self):
        if self.recording:
            print('current recording being stopping...')
            print('number of previously saved frames:\n{0}'.\
                  format(self.num_saved_frame))

            self.recording = False
            sleep(0.02)
            try:
                self.recorder.release_writer()
            except:
                pass
            sleep(0.02)
        print('new recording starting...')
        self.initialise_videorecorder()
        self.recording = True

    @pyqtSlot()
    def on_saveClick(self):
        self.on_start()
        if self.save_btn.isChecked():
            try:
                self.recorder.initialise_writer()
                print('writer initialised')
                sleep(0.02)
                self.save = self.save_btn.isChecked()
            except:
                print('couldn\'t initialise writer')
        else:
            try:
                self.recorder.release_writer()
            except:
                print('couldn\'t release writer')
                pass

    @pyqtSlot()
    def on_stop(self):
        print('current recording being stopping...')
        print('number of previously saved frames:\n{0}'.\
                  format(self.num_saved_frame))
        self.recording = False
        self.save = False
        self.save_btn.setChecked(self.save)

        try:
            self.recorder.release_writer()
            self.num_saved_frame = 0
        except:
            pass

    @pyqtSlot()
    def on_ROIinit(self):
        print('initiliase ROI')
        self.initialise_ROI()

    @pyqtSlot()
    def on_quit(self):
        print('stopping threads...')
        self.flowOn = False
        self.resetARD()
        self.recording = False
        self.trialOn = False
        sleep(0.5)
        print('number saved frames:\n{0}'.\
                  format(self.num_saved_frame))
        try:
            self.recorder.release_writer()
        except:
            pass
        try:
            self.recorder.release_camera()
        except:
            pass

        self.recordingThread.stop()
        self.trialThread.stop()

    def resetARD(self):
        if self.flowOn == False:
            if self.ARD:
                print('0')
                self.Ard.sendChar('0')
        if self.flowOn == True:
            if self.ARD:
                self.Ard.sendChar('1')

    def resetFlowRate(self):
        if self.ARD:
            self.Ard.sendChar('r')
            self.resetARD()

    def resetPath(self):
        self.dt = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")[2:]
        self.path = self.get_path()
        self.path_bx.setText(self.path)

    def kill_threads(self):
        self.recording = False
        self.trialOn = False

    def start_recording(self):
        while self.recording:
            self.frame_loop()

    def start_trial(self):
        while self.trialOn:
            self.trial_loop()

    ##########################
    ##### Thread functions
    ##########################
    def trial_loop(self):
        time_ = self.trialTimer.get_time()
        self.time_left = self.trialTime - int(time_)
        self.Timer_tbox.setText(str(self.time_left))
        if time_ > self.trialTime:
            print('new trial')
            self.flowOn = True
            self.resetARD()
            sleep(int(self.trialSleepTime))
            self.flowOn = False
            self.resetARD()
            self.trialTimer.restart()

    def frame_loop(self):
        self.gray = self.grab_frame()
        self.blur = self.Tracker.blur_frame(self.gray)
        self.mvAvgFrame = self.update_avg()
        self.fD = self.Tracker.delta_frame(self.mvAvgFrame, self.blur)

        self.mask, self.masked = self.Tracker.mask_frame(self.fD,
                                                         pVal=self.pVal,
                                                         pVal_mx=self.pVal_mx)

        self.fD_, self.keypoints, self.num_fish_detected, self.max_a\
        = self.Tracker.get_frame_contours(self.masked, self.fD)

        self.maxArea_box.setText(str(self.max_a))
        self.num_detected_box.setText(str(self.num_fish_detected))

        if self.save:
            self.num_saved_frame += 1
            try:
                self.recorder.save_frame(self.gray)
            except:
                print('couldn\'t save file')
        self.show_frame()

    ##########################
    ##### detection functions
    ##########################

    def grab_frame(self):
        try:
            (grabbed, frame) = self.camera.read()
            self.frame = cv2.resize(frame, (self.imW, self.imH))
            self.gray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)
            #self.frame = cv2.cvtColor(self.frame , cv2.COLOR_BGR2HSV)[:,:,1] # saturation
        except:
            print('couldn\'t grab frame')
            pass
        return self.gray

    def update_avg(self):
        if self.mvAvgFrame is None:
            self.mvAvgFrame = self.blur
        else:
            self.ite += 1
            fr = self.ite
            if fr > 10000:
                print('reset')
                self.ite = 1
                self.mvAvgFrame = self.mvAvgFrame
            else:
                self.mvAvgFrame = self.mvAvgFrame * (
                    fr / (fr + 1)) + self.blur / (fr + 1)
        return self.mvAvgFrame

    def show_frame(self):
        if self.ite % 4 == 0:
            self.imv1.setImage(self.gray.T)
        elif self.ite % 4 == 1:
            self.imv4.setImage(self.mvAvgFrame.T.astype('uint8'))
        elif self.ite % 4 == 2:
            self.imv2.setImage(self.fD_.swapaxes(0, 1))
        elif self.ite % 4 == 3:
            self.imv3.setImage(self.mask.T)
예제 #20
0
파일: viewer3.py 프로젝트: mjirik/lisa
    print("deprecated import of seg2fem")

    import seg2fem

import misc
'''
Používané globální proměnné
'''
plane = vtk.vtkPlane()
normal = None
coordinates = None
iren = vtk.vtkRenderWindowInteractor()
surface = vtk.vtkDataSetSurfaceFilter()
app = QApplication(sys.argv)
label = QtWidgets.QLabel()
myLayout = QGridLayout()
widget = vtk.vtkSphereSource()
planeWidget = vtk.vtkImplicitPlaneWidget()
'''
Kód grafického editoru resekční linie. Tento kód byl automaticky vygenerován pomocí programu Qt Designer
'''
##------------------------------------------------------------------------------------------
try:
    _encoding = QtWidgets.QApplication.UnicodeUTF8

    def _translate(context, text, disambig):
        return QtCore.QCoreApplication.translate(context, text, disambig,
                                                 _encoding)
except AttributeError:

    def _translate(context, text, disambig):
예제 #21
0
    def initUI(self):
        cw = QWidget()
        self.setCentralWidget(cw)
        grid = QGridLayout()
        grid.setSpacing(15)

        # status bar
        self.statusBar().showMessage('Ready')

        font_label = QFont()
        font_label.setBold(True)
        ################ dicom reader
        rstart = 0
        text_dcm = QLabel('DICOM reader')
        text_dcm.setFont(font_label)
        self.text_dcm_dir = QLabel('DICOM dir:')
        self.text_dcm_data = QLabel('DICOM data:')
        self.text_dcm_out = QLabel('output file:')
        grid.addWidget(text_dcm, rstart + 0, 1, 1, 4)
        grid.addWidget(self.text_dcm_dir, rstart + 1, 1, 1, 4)
        grid.addWidget(self.text_dcm_data, rstart + 2, 1, 1, 4)
        grid.addWidget(self.text_dcm_out, rstart + 3, 1, 1, 4)
        btn_dcmdir = QPushButton("Load DICOM", self)
        btn_dcmdir.clicked.connect(self.loadDcmDir)
        btn_dcmred = QPushButton("Organ Segmentation", self)
        btn_dcmred.clicked.connect(self.organSegmentation)
        btn_dcmcrop = QPushButton("Crop", self)
        btn_dcmcrop.clicked.connect(self.cropDcm)
        btn_dcmsave = QPushButton("Save DCM", self)
        btn_dcmsave.clicked.connect(self.saveDcm)
        grid.addWidget(btn_dcmdir, rstart + 4, 1)
        grid.addWidget(btn_dcmred, rstart + 4, 2)
        grid.addWidget(btn_dcmcrop, rstart + 4, 3)
        grid.addWidget(btn_dcmsave, rstart + 4, 4)

        hr = QFrame()
        hr.setFrameShape(QFrame.HLine)
        grid.addWidget(hr, rstart + 5, 0, 1, 6)

        # quit
        btn_quit = QPushButton("Quit", self)
        btn_quit.clicked.connect(self.quit)
        grid.addWidget(btn_quit, 24, 2, 1, 2)

        cw.setLayout(grid)
        self.setWindowTitle('liver-surgery')
        self.show()
예제 #22
0
파일: mshow.py 프로젝트: lycying/seeking
    def invoke(self):
        searchInput = QLineEdit()
        normalInput = QPlainTextEdit()
        normalInput.setMaximumHeight(100)
        searchBtn = QPushButton("Search")
        sayBtn = QPushButton("Hmm..")

        listTops = QWidget()

        layoutWidget = QGridLayout()
        layoutWidget.addWidget(searchInput, 1, 0)
        layoutWidget.addWidget(searchBtn, 1, 1)
        layoutWidget.addWidget(normalInput, 2, 0)
        layoutWidget.addWidget(sayBtn, 2, 1)
        layoutWidget.addWidget(listTops, 3, 0, 8, 1)

        self.setLayout(layoutWidget)
예제 #23
0
#!/usr/bin/env python3

import finplot as fplt
from functools import lru_cache
from PyQt5.QtWidgets import QGraphicsView, QComboBox, QLabel
from PyQt5.QtGui import QApplication, QGridLayout
from threading import Thread
import yfinance as yf

app = QApplication([])
win = QGraphicsView()
win.setWindowTitle('TradingView wannabe')
layout = QGridLayout()
win.setLayout(layout)
win.resize(600, 500)

combo = QComboBox()
combo.setEditable(True)
[
    combo.addItem(i) for i in
    'AMRK FB GFN REVG TSLA TWTR WMT CT=F GC=F ^FTSE ^N225 EURUSD=X ETH-USD'.
    split()
]
layout.addWidget(combo, 0, 0, 1, 1)
info = QLabel()
layout.addWidget(info, 0, 1, 1, 1)

ax = fplt.create_plot_widget(win, init_zoom_periods=100)
win.axs = [ax]  # finplot requres this property
layout.addWidget(ax.ax_widget, 1, 0, 1, 2)
class EditorSchemeDesigner(QDialog):
    """Editor Scheme Designer Class Widget"""
    def __init__(self, scheme, parent):
        super(EditorSchemeDesigner, self).__init__(parent, Qt.Dialog)
        self.original_style = copy.copy(resources.CUSTOM_SCHEME)
        self._avoid_on_loading, self.saved, self._components = True, False, {}
        self.setWindowTitle(translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER)
        self.setMinimumSize(450, 480)
        self.setMaximumSize(500, 900)
        self.resize(450, 600)

        # all layouts and groupboxes
        group0 = QGroupBox(translations.TR_PROJECT_NAME)  # scheme filename
        group1 = QGroupBox(translations.TR_PROJECT_PROPERTIES)  # properties
        group2 = QGroupBox(translations.TR_PREVIEW)  # quick preview thingy
        group0_hbox, group1_vbox = QHBoxLayout(group0), QVBoxLayout(group1)
        this_dialog_vbox, group2_vbox = QVBoxLayout(self), QVBoxLayout(group2)
        self._grid, scrollArea, frame = QGridLayout(), QScrollArea(), QFrame()

        # widgets
        self.line_name, btnSave = QLineEdit(), QPushButton(
            translations.TR_SAVE)
        self.line_name.setPlaceholderText(getuser().capitalize() + "s_scheme")
        group0_hbox.addWidget(self.line_name)
        group0_hbox.addWidget(btnSave)
        self.connect(btnSave, SIGNAL("clicked()"), self.save_scheme)
        _demo = "<center>" + ascii_letters  # demo text for preview
        self.preview_label1, self.preview_label2 = QLabel(_demo), QLabel(_demo)
        group2_vbox.addWidget(self.preview_label1)
        group2_vbox.addWidget(self.preview_label2)

        # rows titles
        self._grid.addWidget(QLabel("<b>" + translations.TR_PROJECT_NAME), 0,
                             0)
        self._grid.addWidget(QLabel("<b>" + translations.TR_CODE), 0, 1)
        self._grid.addWidget(
            QLabel("<b>" + translations.TR_EDITOR_SCHEME_PICK_COLOR), 0, 2)

        # fill rows
        for key in sorted(tuple(resources.COLOR_SCHEME.keys())):
            self.add_item(key, scheme)
        self.preview_label1.setStyleSheet('background:transparent')
        self.preview_label2.setStyleSheet('color:     transparent')

        # fill the scroll area
        frame.setLayout(self._grid)
        scrollArea.setWidget(frame)
        group1_vbox.addWidget(scrollArea)

        # put groups on the dialog
        this_dialog_vbox.addWidget(group1)
        this_dialog_vbox.addWidget(group2)
        this_dialog_vbox.addWidget(group0)
        self._avoid_on_loading = self._modified = False

    def add_item(self, key, scheme):
        """Take key and scheme arguments and fill up the grid with widgets."""
        row = self._grid.rowCount()
        self._grid.addWidget(QLabel(key), row, 0)
        isnum = isinstance(scheme[key], int)
        text = QLineEdit(str(scheme[key]))
        self._grid.addWidget(text, row, 1)
        if not isnum:
            btn = QPushButton()
            btn.setToolTip(translations.TR_EDITOR_SCHEME_PICK_COLOR)
            self.apply_button_style(btn, scheme[key])
            self._grid.addWidget(btn, row, 2)

            self.connect(text, SIGNAL("textChanged(QString)"),
                         lambda: self.apply_button_style(btn, text.text()))
            self.connect(btn, SIGNAL("clicked()"),
                         lambda: self._pick_color(text, btn))
        else:
            self.connect(text, SIGNAL("textChanged(QString)"),
                         self._preview_style)
        self._components[key] = (text, isnum)

    def apply_button_style(self, btn, color_name):
        """Take a button widget and color name and apply as stylesheet."""
        if QColor(color_name).isValid():
            self._modified = True
            btn.setStyleSheet('background:' + color_name)
            self.preview_label1.setStyleSheet('background:' + color_name)
            self.preview_label2.setStyleSheet('color:' + color_name)
            self._preview_style()

    def _pick_color(self, lineedit, btn):
        """Pick a color name using lineedit and button data."""
        color = QColorDialog.getColor(QColor(lineedit.text()), self,
                                      translations.TR_EDITOR_SCHEME_PICK_COLOR)
        if color.isValid():
            lineedit.setText(str(color.name()))
            self.apply_button_style(btn, color.name())

    def _preview_style(self):
        """Live preview style on editor."""
        if self._avoid_on_loading:
            return
        scheme = {}
        keys = sorted(tuple(resources.COLOR_SCHEME.keys()))
        for key in keys:
            isnum = self._components[key][1]
            if isnum:
                num = self._components[key][0].text()
                if num.isdigit():
                    scheme[key] = int(num)
                else:
                    scheme[key] = 0
            else:
                scheme[key] = self._components[key][0].text()
        resources.CUSTOM_SCHEME = scheme
        editorWidget = self._get_editor()
        if editorWidget is not None:
            editorWidget.restyle(editorWidget.lang)
            editorWidget.highlight_current_line()
        return scheme

    def _get_editor(self):
        """Return current Editor."""
        main_container = IDE.get_service("main_container")
        editorWidget = main_container.get_current_editor()
        return editorWidget

    def reject(self):
        """Reject this dialog."""
        if self._modified:
            answer = QMessageBox.No
            answer = QMessageBox.question(
                self, translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER,
                (translations.TR_IDE_CONFIRM_EXIT_TITLE + ".\n" +
                 translations.TR_PREFERENCES_GENERAL_CONFIRM_EXIT + "?"),
                QMessageBox.Yes, QMessageBox.No)
            if answer == QMessageBox.No:
                return
        super(EditorSchemeDesigner, self).reject()

    def hideEvent(self, event):
        """Handle Hide event on this dialog."""
        super(EditorSchemeDesigner, self).hideEvent(event)
        resources.CUSTOM_SCHEME = self.original_style
        editorWidget = self._get_editor()
        if editorWidget is not None:
            editorWidget.restyle(editorWidget.lang)

    def _is_valid_scheme_name(self, name):
        """Check if a given name is a valid name for an editor scheme.
        Params:
            name := the name to check
        Returns:
            True if and only if the name is okay to use for a scheme. """
        return name not in ('', 'default')

    def save_scheme(self):
        """Save current scheme."""
        name = self.line_name.text().strip()
        if not self._is_valid_scheme_name(name):
            QMessageBox.information(
                self, translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER,
                translations.TR_SCHEME_INVALID_NAME)
            return
        fileName = ('{0}.color'.format(
            file_manager.create_path(resources.EDITOR_SKINS, name)))
        answer = True
        if file_manager.file_exists(fileName):
            answer = QMessageBox.question(
                self, translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER,
                translations.TR_WANT_OVERWRITE_FILE +
                ": {0}?".format(fileName), QMessageBox.Yes, QMessageBox.No)

        if answer in (QMessageBox.Yes, True):
            scheme = self._preview_style()
            self.original_style = copy.copy(scheme)
            json_manager.save_editor_skins(fileName, scheme)
            self._modified = False
            self.saved = True
            qsettings = IDE.ninja_settings()
            qsettings.setValue('preferences/editor/scheme', name)
            QMessageBox.information(
                self, translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER,
                translations.TR_SCHEME_SAVED + ": {0}.".format(fileName))
            self.close()
        elif answer == QMessageBox.Yes:
            QMessageBox.information(
                self, translations.TR_PREFERENCES_EDITOR_SCHEME_DESIGNER,
                translations.TR_INVALID_FILENAME)