Exemplo n.º 1
0
class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()

        self.setWindowTitle("Pyside2 Grid Layout")
        self.setGeometry(300, 300, 500, 500)
        self.createLayout()
        vbox = QVBoxLayout()
        vbox.addWidget(self.groupBox)
        self.setLayout(vbox)

    def createLayout(self):
        self.groupBox = QGroupBox("Please Choose One Language  ")
        self.groupBox.setFont(QFont("Sanserif", 13))
        gridlayout = QGridLayout()
        button1 = QPushButton("CSS", self)
        gridlayout.addWidget(button1, 0, 0)
        button2 = QPushButton("C++", self)
        gridlayout.addWidget(button2, 0, 1)
        button3 = QPushButton("Java", self)
        gridlayout.addWidget(button3, 1, 0)
        button4 = QPushButton("JavaScript", self)
        gridlayout.addWidget(button4, 1, 1)

        self.groupBox.setLayout(gridlayout)
Exemplo n.º 2
0
def create_group_box(parent, text):
    font = QFont()
    font.setBold(True)
    group_box = QGroupBox(text, parent)
    group_box.setFont(font)
    group_box.setAlignment(Qt.AlignHCenter)
    group_box.setFlat(False)
    return group_box
Exemplo n.º 3
0
    def _setupFilterGroupBox(self, layout):
        filterGroupBox = QGroupBox(
            maya.stringTable['y_simpleSelector.kCollectionFilters'])
        font = QFont()
        font.setBold(True)
        filterGroupBox.setFont(font)
        filterGroupBox.setContentsMargins(0, utils.dpiScale(12), 0, 0)
        self.filtersGroupBoxLayout = Layout()
        self.filtersGroupBoxLayout.setVerticalSpacing(utils.dpiScale(2))

        self._setupFilterUI(self.filtersGroupBoxLayout)

        filterGroupBox.setLayout(self.filtersGroupBoxLayout)
        layout.addWidget(filterGroupBox)
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("sttting icon")
        self.setGeometry(300, 300, 500, 400)
        self.setIcon()
        # showing a hint, or tooltip
        self.setToolTip("this is window")

        self.createLayout()
        vbox = QVBoxLayout()
        vbox.addWidget(self.groupBox)
        self.setLayout(vbox)
        self.show()

    def setIcon(self):
        appIcon = QIcon("Screenshot from 2019-10-15 09-33-25.png")
        self.setWindowIcon(appIcon)

    def createLayout(self):
        self.groupBox = QGroupBox("please choose ine languages")
        self.groupBox.setFont(QFont("Sanserif", 13))
        gridlayout = QGridLayout()

        button = QPushButton("CSS", self)
        button.setIcon(QIcon("Screenshot from 2019-10-15 09-33-25.png"))
        gridlayout.addWidget(button, 0, 0)

        button1 = QPushButton("C++", self)
        button1.setIcon(QIcon("Screenshot from 2019-10-15 09-33-25.png"))
        gridlayout.addWidget(button1, 0, 1)

        button2 = QPushButton("Python", self)
        button2.setIcon(QIcon("Screenshot from 2019-10-15 09-33-25.png"))
        gridlayout.addWidget(button2, 1, 0)

        button3 = QPushButton("javascript", self)
        button3.setIcon(QIcon("Screenshot from 2019-10-15 09-33-25.png"))
        gridlayout.addWidget(button3, 1, 1)

        button4 = QPushButton("c#", self)
        button4.setIcon(QIcon("Screenshot from 2019-10-15 09-33-25.png"))
        gridlayout.addWidget(button4, 2, 0)

        button5 = QPushButton("java", self)
        button5.setIcon(QIcon("Screenshot from 2019-10-15 09-33-25.png"))
        gridlayout.addWidget(button5, 2, 1)

        self.groupBox.setLayout(gridlayout)
Exemplo n.º 5
0
    def _setupAddToCollectionGroupBox(self, layout):
        addToCollectionGroupBox = QGroupBox(
            maya.stringTable['y_staticCollection.kAddToCollection'])
        font = QFont()
        font.setBold(True)
        addToCollectionGroupBox.setFont(font)
        addToCollectionGroupBox.setContentsMargins(0, utils.dpiScale(12), 0, 0)
        self.addToCollectionGroupBoxLayout = propEdLayout.Layout()
        self.addToCollectionGroupBoxLayout.setVerticalSpacing(
            utils.dpiScale(2))

        self._setupStaticSelector()

        addToCollectionGroupBox.setLayout(self.addToCollectionGroupBoxLayout)
        layout.addWidget(addToCollectionGroupBox)
Exemplo n.º 6
0
class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle(
            "Pyside2 Grid Layout")  # Configure le titre de la fenêtre
        self.setGeometry(300, 300, 500,
                         400)  # Configure la taille de la fenêtre

        self.setIcon()

        self.createGridLayout()
        vbox = QVBoxLayout()
        vbox.addWidget(self.groupBox)
        self.setLayout(vbox)

    def setIcon(self):
        appIcon = QIcon("icon.png")
        self.setWindowIcon(appIcon)

    def createGridLayout(self):
        self.groupBox = QGroupBox("Please choose one laguage")
        self.groupBox.setFont(QFont("Sanserif", 13))
        gridLayout = QGridLayout()

        button = QPushButton("C++", self)
        button.setIcon(QIcon("icon.png"))
        gridLayout.addWidget(button, 0, 0)

        button2 = QPushButton("Css", self)
        button2.setIcon(QIcon("icon.png"))
        gridLayout.addWidget(button2, 0, 1)

        button3 = QPushButton("Javascript", self)
        button3.setIcon(QIcon("icon.png"))
        gridLayout.addWidget(button3, 1, 0)

        button4 = QPushButton("C#", self)
        button4.setIcon(QIcon("icon.png"))
        gridLayout.addWidget(button4, 1, 1)

        button5 = QPushButton("Python", self)
        button5.setIcon(QIcon("icon.png"))
        gridLayout.addWidget(button5, 2, 0)

        self.groupBox.setLayout(gridLayout)
Exemplo n.º 7
0
class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle(
            "Pyside2 Layout Management")  # Configure le titre de la fenêtre
        self.setGeometry(300, 300, 500,
                         400)  # Configure la taille de la fenêtre

        self.setIcon()

        self.createLayout()
        vbox = QVBoxLayout()
        vbox.addWidget(self.groupBox)
        self.setLayout(vbox)

    def setIcon(self):
        appIcon = QIcon("icon.png")
        self.setWindowIcon(appIcon)

    def createLayout(self):
        self.groupBox = QGroupBox("Please choose one language")
        self.groupBox.setFont(QFont("Sanserif", 13))

        hbox = QHBoxLayout()

        button = QPushButton("CSS", self)
        button.setIcon(QIcon("icon.png"))
        button.setMinimumWidth(40)
        hbox.addWidget(button)

        button2 = QPushButton("C++", self)
        button2.setIcon(QIcon("icon.png"))
        button2.setMinimumWidth(40)
        hbox.addWidget(button2)

        button3 = QPushButton("Javascript", self)
        button3.setIcon(QIcon("icon.png"))
        button3.setMinimumWidth(40)
        hbox.addWidget(button3)

        self.groupBox.setLayout(hbox)
Exemplo n.º 8
0
class Main(QWidget):
    def __init__(self):
        super().__init__()

        self.groupBox = QGroupBox("Meniu")
        self.setWindowTitle("Covid-19 duomenys")
        self.setGeometry(300, 300, 500, 400)
        self.setMinimumHeight(500)
        self.setMinimumWidth(400)
        self.setMaximumHeight(500)
        self.setMaximumWidth(400)

        self.GridLayout()
        vbox = QVBoxLayout()
        vbox.addWidget(self.groupBox)
        self.setLayout(vbox)
        self.show()

    def GridLayout(self):
        self.groupBox.setFont(QFont("Sanserif", 13))
        gridLayout = QGridLayout()

        button1 = QPushButton("Statistika", self)
        gridLayout.addWidget(button1, 0, 1)
        button1.clicked.connect(self.on_pushButton_clicked)
        self.dialog = Second(self)

        button2 = QPushButton("Įšėjimas", self)
        gridLayout.addWidget(button2, 1, 1)
        button2.clicked.connect(self.exit_app)

        self.groupBox.setLayout(gridLayout)

    def exit_app(self):
        self.close()

    def on_pushButton_clicked(self):
        self.hide()
        self.dialog.show()
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("sttting icon")
        self.setGeometry(300, 300, 500, 400)
        self.setIcon()
        # showing a hint, or tooltip
        self.setToolTip("this is window")

        self.createLayout()
        vbox = QVBoxLayout()
        vbox.addWidget(self.groupBox)
        self.setLayout(vbox)
        self.show()

    def setIcon(self):
        appIcon = QIcon("Screenshot from 2019-10-15 09-33-25.png")
        self.setWindowIcon(appIcon)

    def createLayout(self):
        self.groupBox = QGroupBox("please choose ine languages")
        self.groupBox.setFont(QFont("Sanserif", 13))
        hbox = QHBoxLayout()

        button = QPushButton("CSS", self)
        button.setIcon(QIcon("Screenshot from 2019-10-15 09-33-25.png"))
        button.setMinimumHeight(40)
        hbox.addWidget(button)

        button1 = QPushButton("C++", self)
        button1.setIcon(QIcon("Screenshot from 2019-10-15 09-33-25.png"))
        button1.setMinimumHeight(40)
        hbox.addWidget(button1)

        button2 = QPushButton("Python", self)
        button2.setIcon(QIcon("Screenshot from 2019-10-15 09-33-25.png"))
        button2.setMinimumHeight(40)
        hbox.addWidget(button2)
        self.groupBox.setLayout(hbox)
Exemplo n.º 10
0
class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()

        self.setWindowTitle("Pyside2 Simple Application")
        self.setGeometry(300, 300, 500, 500)
        self.createLayout()
        vbox = QVBoxLayout()
        vbox.addWidget(self.groupBox)
        self.setLayout(vbox)

    def createLayout(self):
        self.groupBox = QGroupBox("Please Choose One Language  ")
        self.groupBox.setFont(QFont("Sanserif", 13))
        hbox = QHBoxLayout()
        button1 = QPushButton("CSS", self)
        hbox.addWidget(button1)
        button2 = QPushButton("C++", self)
        hbox.addWidget(button2)
        button3 = QPushButton("Java", self)
        hbox.addWidget(button3)

        self.groupBox.setLayout(hbox)
Exemplo n.º 11
0
    def createChoiceBox(self):
        #生成顯示玩家&電腦出拳的畫面
        self.h_layout = QHBoxLayout()

        box_font = QFont()
        box_font.setPointSize(16)

        choice_label_font = QFont()
        choice_label_font.setPointSize(80)

        #產生顯示玩家選擇的畫面,並使用 QGroupBox & QHBoxLayout 排版
        player_groupbox = QGroupBox("玩家")
        player_groupbox.setFont(box_font)

        self.player_choice_label = QLabel(self.paper)
        self.player_choice_label.setFixedSize(120, 150)
        self.player_choice_label.setFont(choice_label_font)

        player_layout = QHBoxLayout()
        player_layout.addWidget(self.player_choice_label)
        player_groupbox.setLayout(player_layout)

        # 產生顯示電腦選擇的畫面,並使用 QGroupBox & QHBoxLayout 排版
        com_groupbox = QGroupBox("電腦")
        com_groupbox.setFont(box_font)

        self.com_choice_label = QLabel(self.paper)
        self.com_choice_label.setFixedSize(120, 150)
        self.com_choice_label.setFont(choice_label_font)

        com_layout = QHBoxLayout()
        com_layout.addWidget(self.com_choice_label)
        com_groupbox.setLayout(com_layout)

        #將玩家&電腦的畫面用 GHBoxLayout 排版
        self.h_layout.addWidget(player_groupbox)
        self.h_layout.addWidget(com_groupbox)
Exemplo n.º 12
0
class DataBrowserMain(QWidget):
    sliceUpdated = Signal(int, int, int, int)

    def __init__(self, parent):
        super(DataBrowserMain, self).__init__(parent)

        # data import
        self.brkraw_obj = self.parent().brkraw_obj
        self.selectedScan = None
        self.selectedScanTR = None

        self.set_viewer_frame()
        self.set_controller_frame()
        self.set_gridlayouts()
        self.set_font()
        # self.set_palette()  # TODO
        self.set_size()
        self.set_objectnames()
        self.set_texts()
        self.ratio_container = []
        self.init_connection()
        self.inactivate_widgets()  # Inactivate during startup

    def init_connection(self):
        self.parent().dataSelected.connect(
            self.selectScanEvent)  # run selectScanEvent when data selected
        self.event_timer = QTimer()
        self.event_timer.timeout.connect(self.sliceUpdateEvent)  #
        self.sliceUpdated.connect(self.updateImage)

        self.xaxis_slider.valueChanged.connect(self.xaxis_spinbox.setValue)
        self.xaxis_spinbox.valueChanged.connect(self.xaxis_slider.setValue)
        self.yaxis_slider.valueChanged.connect(self.yaxis_spinbox.setValue)
        self.yaxis_spinbox.valueChanged.connect(self.yaxis_slider.setValue)
        self.zaxis_slider.valueChanged.connect(self.zaxis_spinbox.setValue)
        self.zaxis_spinbox.valueChanged.connect(self.zaxis_slider.setValue)
        self.frame_slider.valueChanged.connect(self.frame_spinbox.setValue)
        self.frame_spinbox.valueChanged.connect(self.frame_slider.setValue)

        self.axial_view.pointed.connect(self.axialview_pointing_event)
        self.sagittal_view.pointed.connect(self.sagittalview_pointing_event)
        self.coronal_view.pointed.connect(self.coronalview_pointing_event)

        self.connect_sliders_to_update()

    def sagittalview_pointing_event(self, pos_x, pos_y, meta):
        max_x = self.yaxis_slider.maximum()
        max_y = self.zaxis_slider.maximum()

        # print(pos_x, pos_y, max_x, max_y)
        self.yaxis_slider.setValue(int(max_x * pos_x))
        self.zaxis_slider.setValue(max_y - int(max_y * pos_y))
        # print(int(max_x * pos_x), int(max_y * pos_y))

    def axialview_pointing_event(self, pos_x, pos_y, meta):
        max_x = self.yaxis_slider.maximum()
        max_y = self.xaxis_slider.maximum()

        # print(pos_x, pos_y, max_x, max_y)
        self.yaxis_slider.setValue(int(max_x * pos_x))
        self.xaxis_slider.setValue(int(max_y * pos_y))
        # print(int(max_x * pos_x), int(max_y * pos_y))

    def coronalview_pointing_event(self, pos_x, pos_y, meta):
        max_x = self.xaxis_slider.maximum()
        max_y = self.zaxis_slider.maximum()

        # print(pos_x, pos_y, max_x, max_y)
        self.xaxis_slider.setValue(int(max_x * pos_x))
        self.zaxis_slider.setValue(max_y - int(max_y * pos_y))
        # print(int(max_x * pos_x), int(max_y * pos_y))

    def sliderChangeEvent(self):
        self.event_timer.start(10)

    def sliceUpdateEvent(self):
        # This will executed only when timer timeout
        x = self.xaxis_slider.value()
        y = self.yaxis_slider.value()
        z = self.zaxis_slider.value()
        t = self.frame_slider.value()
        self.sliceUpdated.emit(x, y, z, t)
        self.event_timer.stop()

    @staticmethod
    def slice_data(dataobj, slice_orient, slice_num):
        if slice_orient == 'axial':
            sliced_data = dataobj[:, :, slice_num]
        elif slice_orient == 'sagittal':
            sliced_data = dataobj[:, slice_num, ::-1]
        elif slice_orient == 'coronal':
            sliced_data = dataobj[slice_num, :, ::-1]
        else:
            popup_error_dialog(UnexpectedError.message)
            return None
        return sliced_data

    def updateImage(self, x, y, z, frame):
        if len(self.selectedScan.shape) == 4:
            dataobj = self.selectedScan[:, :, :, frame]
        else:
            dataobj = self.selectedScan[...]

        data_xy = self.slice_data(dataobj, 'axial', z)
        data_yz = self.slice_data(dataobj, 'sagittal', x)
        data_xz = self.slice_data(dataobj, 'coronal', y)
        ratio_xy, ratio_yz, ratio_xz = self.ratio_container
        # ratio_xy, ratio_yz, ratio_xz = 1, 1, 1

        qm_xy = convert_arr2qpixmap(data_xy, ratio_xy)
        qm_yz = convert_arr2qpixmap(data_yz, ratio_yz)
        qm_xz = convert_arr2qpixmap(data_xz, ratio_xz)

        self.axial_view.setPixmap(qm_xy)
        self.sagittal_view.setPixmap(qm_yz)
        self.coronal_view.setPixmap(qm_xz)

    def selectScanEvent(self, delivery_package: list):
        """ this event is occurring when a scan selected on scanlist """
        self.axial_view.setEnabled(True)
        self.sagittal_view.setEnabled(True)
        self.coronal_view.setEnabled(True)
        self.selectedScan, affine, resol, self.selectedScanTR, is_localizer = delivery_package
        self.selectedScanTR /= 1000

        from slfmri.imgman import reorient_to_ras, determine_slice_plane
        slice_plane_ref = dict(sagittal=0, coronal=1, axial=2)

        if is_localizer:
            img_container = dict()
            for i, aff in enumerate(affine):
                size = config.get('ImageViewer', 'size')
                data = self.selectedScan[..., i]
                slice_plane = determine_slice_plane(2, aff, resol)
                ras_data, ras_resol = reorient_to_ras(data[:, :, np.newaxis],
                                                      aff, resol)
                slice_axis = slice_plane_ref[slice_plane]
                ras_data = ras_data.mean(slice_axis)
                ras_resol = np.delete(ras_resol, slice_axis)
                qpixmap = convert_arr2qpixmap(ras_data, ras_resol, size)
                img_container[slice_plane] = qpixmap

            self.update_axisview(img_container)
        else:
            # other than localizer
            self.init_data(self.selectedScan)
            matrix_size = np.asarray(self.selectedScan.shape)
            resol = np.asarray(resol)
            fov = matrix_size[:3] * resol
            self.ratio_container = [
                fov[0] / fov[1], fov[1] / fov[2], fov[0] / fov[2]
            ]
            # reset value
            init_x, init_y, init_z = (np.asarray(self.selectedScan.shape[:3]) /
                                      2.0).astype(int)
            init_f = 0

            self.disconnect_sliders_to_update()
            self.xaxis_slider.setValue(init_x)
            self.yaxis_slider.setValue(init_y)
            self.zaxis_slider.setValue(init_z)
            self.frame_slider.setValue(init_f)
            self.connect_sliders_to_update()
            self.updateImage(init_x, init_y, init_z, init_f)

    def connect_sliders_to_update(self):
        # connect to check slice update
        self.xaxis_slider.valueChanged.connect(self.sliderChangeEvent)
        self.yaxis_slider.valueChanged.connect(self.sliderChangeEvent)
        self.zaxis_slider.valueChanged.connect(self.sliderChangeEvent)
        self.frame_slider.valueChanged.connect(self.sliderChangeEvent)

    def disconnect_sliders_to_update(self):
        # disconnect to check slice update
        self.xaxis_slider.valueChanged.disconnect(self.sliderChangeEvent)
        self.yaxis_slider.valueChanged.disconnect(self.sliderChangeEvent)
        self.zaxis_slider.valueChanged.disconnect(self.sliderChangeEvent)
        self.frame_slider.valueChanged.disconnect(self.sliderChangeEvent)

    def init_data(self, dataobj):
        self.slicecontrol_pane.setEnabled(True)
        dim = len(dataobj.shape)
        if dim == 3:
            size_x, size_y, size_z = dataobj.shape
            size_frame = None
        elif dim == 4:
            size_x, size_y, size_z, size_frame = dataobj.shape
        else:
            popup_error_dialog(UnexpectedError.message)
            return None

        # init sliders and spinboxes
        self.xaxis_slider.setRange(0, size_x - 1)
        self.yaxis_slider.setRange(0, size_y - 1)
        self.zaxis_slider.setRange(0, size_z - 1)

        self.xaxis_spinbox.setRange(0, size_x - 1)
        self.yaxis_spinbox.setRange(0, size_y - 1)
        self.zaxis_spinbox.setRange(0, size_z - 1)

        if dim == 3:
            self.frame_label.setDisabled(True)
            self.frame_slider.setDisabled(True)
            self.frame_spinbox.setDisabled(True)
        else:
            self.frame_label.setEnabled(True)
            self.frame_slider.setEnabled(True)
            self.frame_spinbox.setEnabled(True)
            self.frame_slider.setRange(0, size_frame - 1)
            self.frame_spinbox.setRange(0, size_frame - 1)

    def update_axisview(self, img_container: dict):
        for view_plane, pixmap in img_container.items():
            if view_plane == 'axial':
                self.axial_view.setPixmap(pixmap)
            elif view_plane == 'sagittal':
                self.sagittal_view.setPixmap(pixmap)
            else:
                self.coronal_view.setPixmap(pixmap)

    def inactivate_widgets(self):
        self.slicecontrol_pane.setDisabled(True)
        self.graph_frame.setDisabled(True)

    def set_navigationmode(self):
        # mouse click will navigate slice.
        pass

    def set_drawingmode(self):
        # roi drawing function
        pass

    def mask_data_handler(self):
        # mask later handler
        pass

    def slider_event_related(self):
        # slider for slicing.
        pass

    def set_viewer_frame(self):
        self.imageframe = QFrame(self)
        self.axial_view = SliceViewer(self.imageframe)
        self.axial_view.setDisabled(True)
        self.sagittal_view = SliceViewer(self.imageframe)
        self.sagittal_view.setDisabled(True)
        self.coronal_view = SliceViewer(self.imageframe)
        self.coronal_view.setDisabled(True)

        # TODO: Will reactivate these on later version
        # self.axial_title = QLabel(self.imageframe)
        # self.coronal_title = QLabel(self.imageframe)
        # self.sagittal_title = QLabel(self.imageframe)
        #
        # self.axialL_label = QLabel(self.imageframe)
        # self.axialA_label = QLabel(self.imageframe)
        # self.axialR_label = QLabel(self.imageframe)
        # self.axialP_label = QLabel(self.imageframe)
        #
        # self.sagittalS_label = QLabel(self.imageframe)
        # self.sagittalA_label = QLabel(self.imageframe)
        # self.sagittalI_label = QLabel(self.imageframe)
        # self.sagittalP_label = QLabel(self.imageframe)
        #
        # self.coronalL_label = QLabel(self.imageframe)
        # self.coronalS_label = QLabel(self.imageframe)
        # self.coronalR_label = QLabel(self.imageframe)
        # self.coronalI_label = QLabel(self.imageframe)
        #
        # self.axial_title.setTextFormat(Qt.MarkdownText)
        # self.axialL_label.setTextFormat(Qt.MarkdownText)
        # self.axialA_label.setTextFormat(Qt.MarkdownText)
        # self.axialR_label.setTextFormat(Qt.MarkdownText)
        # self.axialP_label.setTextFormat(Qt.MarkdownText)
        #
        # self.sagittal_title.setTextFormat(Qt.MarkdownText)
        # self.sagittalS_label.setTextFormat(Qt.MarkdownText)
        # self.sagittalA_label.setTextFormat(Qt.MarkdownText)
        # self.sagittalI_label.setTextFormat(Qt.MarkdownText)
        # self.sagittalP_label.setTextFormat(Qt.MarkdownText)
        #
        # self.coronal_title.setTextFormat(Qt.MarkdownText)
        # self.coronalL_label.setTextFormat(Qt.MarkdownText)
        # self.coronalS_label.setTextFormat(Qt.MarkdownText)
        # self.coronalR_label.setTextFormat(Qt.MarkdownText)
        # self.coronalI_label.setTextFormat(Qt.MarkdownText)
        #
        # self.axial_title.setAlignment(Qt.AlignCenter)
        # self.axialL_label.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)
        # self.axialA_label.setAlignment(Qt.AlignBottom | Qt.AlignHCenter)
        # self.axialR_label.setAlignment(Qt.AlignLeading | Qt.AlignLeft | Qt.AlignVCenter)
        # self.axialP_label.setAlignment(Qt.AlignHCenter | Qt.AlignTop)
        #
        # self.sagittal_title.setAlignment(Qt.AlignCenter)
        # self.sagittalS_label.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)
        # self.sagittalA_label.setAlignment(Qt.AlignBottom | Qt.AlignHCenter)
        # self.sagittalI_label.setAlignment(Qt.AlignLeading | Qt.AlignLeft | Qt.AlignVCenter)
        # self.sagittalP_label.setAlignment(Qt.AlignHCenter | Qt.AlignTop)
        #
        # self.coronal_title.setAlignment(Qt.AlignCenter)
        # self.coronalL_label.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)
        # self.coronalS_label.setAlignment(Qt.AlignBottom | Qt.AlignHCenter)
        # self.coronalR_label.setAlignment(Qt.AlignLeading | Qt.AlignLeft | Qt.AlignVCenter)
        # self.coronalI_label.setAlignment(Qt.AlignHCenter | Qt.AlignTop)

    def set_controller_frame(self):
        self.controller_frame = QFrame(self)
        self.slicecontrol_pane = QGroupBox(self.controller_frame)
        self.frame_spinbox = QSpinBox(self.slicecontrol_pane)

        self.xaxis_label = QLabel(self.slicecontrol_pane)
        self.yaxis_label = QLabel(self.slicecontrol_pane)
        self.zaxis_label = QLabel(self.slicecontrol_pane)
        self.frame_label = QLabel(self.slicecontrol_pane)

        self.xaxis_slider = QSlider(self.slicecontrol_pane)
        self.yaxis_slider = QSlider(self.slicecontrol_pane)
        self.zaxis_slider = QSlider(self.slicecontrol_pane)
        self.frame_slider = QSlider(self.slicecontrol_pane)

        self.xaxis_spinbox = QSpinBox(self.slicecontrol_pane)
        self.yaxis_spinbox = QSpinBox(self.slicecontrol_pane)
        self.zaxis_spinbox = QSpinBox(self.slicecontrol_pane)

        self.graph_frame = QFrame(self)
        self.graph_view = pg.PlotWidget(self.graph_frame)
        self.graph_view.setBackground('w')

        # TODO: Will reactivate these on later version
        # self.graph_view = QGraphicsView(self.graph_frame)
        # self.graphcontrol_pane = QGroupBox(self.graph_frame)
        # self.addmask_button = QPushButton(self.graphcontrol_pane)
        # self.removemask_button = QPushButton(self.graphcontrol_pane)
        # self.mask_listview = QListView(self.graphcontrol_pane)
        # self.savepng_button = QPushButton(self.graphcontrol_pane)
        # self.savecsv_button = QPushButton(self.graphcontrol_pane)

        self.axial_view.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.sagittal_view.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.coronal_view.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)

        self.xaxis_slider.setOrientation(Qt.Horizontal)
        self.yaxis_slider.setOrientation(Qt.Horizontal)
        self.zaxis_slider.setOrientation(Qt.Horizontal)
        self.frame_slider.setOrientation(Qt.Horizontal)

        self.slicecontrol_pane.setAlignment(Qt.AlignCenter)
        self.xaxis_label.setAlignment(Qt.AlignCenter)
        self.yaxis_label.setAlignment(Qt.AlignCenter)
        self.zaxis_label.setAlignment(Qt.AlignCenter)
        self.frame_label.setAlignment(Qt.AlignCenter)
        # TODO: Will reactivate these on later version
        # self.graphcontrol_pane.setAlignment(Qt.AlignCenter)

    def set_size(self):
        size = int(config.get('ImageViewer', 'size'))
        self.imageframe.setLineWidth(0)
        self.axial_view.setMinimumSize(QSize(size, size))
        self.axial_view.setMaximumSize(QSize(size, size))
        self.axial_view.setLineWidth(0)
        self.sagittal_view.setMinimumSize(QSize(size, size))
        self.sagittal_view.setMaximumSize(QSize(size, size))
        self.sagittal_view.setLineWidth(0)
        self.coronal_view.setMinimumSize(QSize(size, size))
        self.coronal_view.setMaximumSize(QSize(size, size))
        self.coronal_view.setLineWidth(0)

        # TODO: Will reactivate these on later version
        # self.axialL_label.setMinimumSize(QSize(20, 0))
        # self.axialA_label.setMinimumSize(QSize(0, 20))
        # self.axialR_label.setMinimumSize(QSize(20, 0))
        # self.axialP_label.setMinimumSize(QSize(0, 20))
        # self.sagittalS_label.setMinimumSize(QSize(20, 0))
        # self.sagittalA_label.setMinimumSize(QSize(0, 20))
        # self.sagittalI_label.setMinimumSize(QSize(20, 0))
        # self.sagittalP_label.setMinimumSize(QSize(0, 20))
        # self.coronalL_label.setMinimumSize(QSize(20, 0))
        # self.coronalS_label.setMinimumSize(QSize(0, 20))
        # self.coronalR_label.setMinimumSize(QSize(20, 0))
        # self.coronalI_label.setMinimumSize(QSize(0, 20))

        self.controller_frame.setMinimumSize(QSize(300, 300))
        self.controller_frame.setMaximumSize(QSize(400, 300))
        self.graph_frame.setMinimumSize(QSize(0, 300))
        self.graph_frame.setMaximumSize(QSize(4000, 4000))
        self.graph_view.setMaximumSize(QSize(4000, 600))

        # TODO: Will reactivate these on later version
        # self.graphcontrol_pane.setMinimumSize(QSize(300, 0))
        # self.graphcontrol_pane.setMaximumSize(QSize(300, 4000))
        # self.addmask_button.setMinimumSize(QSize(30, 0))
        # self.addmask_button.setMaximumSize(QSize(30, 4000))
        # self.removemask_button.setMinimumSize(QSize(30, 0))
        # self.removemask_button.setMaximumSize(QSize(30, 4000))

    def set_font(self):
        self.arial_8 = QFont()
        self.arial_8.setFamily(u"Arial")
        self.arial_8.setPointSize(8)
        self.setFont(self.arial_8)
        # TODO: Will reactivate these on later version
        # self.axial_title.setFont(self.arial_8)
        # self.coronal_title.setFont(self.arial_8)
        # self.sagittal_title.setFont(self.arial_8)
        # self.axialL_label.setFont(self.arial_8)
        # self.axialA_label.setFont(self.arial_8)
        # self.axialR_label.setFont(self.arial_8)
        # self.axialP_label.setFont(self.arial_8)
        # self.sagittalS_label.setFont(self.arial_8)
        # self.sagittalA_label.setFont(self.arial_8)
        # self.sagittalI_label.setFont(self.arial_8)
        # self.sagittalP_label.setFont(self.arial_8)
        # self.coronalL_label.setFont(self.arial_8)
        # self.coronalS_label.setFont(self.arial_8)
        # self.coronalR_label.setFont(self.arial_8)
        # self.coronalI_label.setFont(self.arial_8)
        self.slicecontrol_pane.setFont(self.arial_8)

        # TODO: Will reactivate these on later version
        # self.xaxis_label.setFont(self.arial_8)
        # self.yaxis_label.setFont(self.arial_8)
        # self.zaxis_label.setFont(self.arial_8)
        # self.frame_label.setFont(self.arial_8)
        # self.graphcontrol_pane.setFont(self.arial_8)
        # self.addmask_button.setFont(self.arial_8)
        # self.removemask_button.setFont(self.arial_8)
        # self.savepng_button.setFont(self.arial_8)
        # self.savecsv_button.setFont(self.arial_8)

    def set_palette(self):
        # Brush
        gray_text = QBrush(QColor(171, 171, 171, 255))
        gray_text.setStyle(Qt.SolidPattern)
        black_background = QBrush(QColor(0, 0, 0, 255))
        black_background.setStyle(Qt.SolidPattern)

        self.orientation_label_palette = QPalette()
        self.orientation_label_palette.setBrush(QPalette.Active,
                                                QPalette.WindowText, gray_text)
        self.orientation_label_palette.setBrush(QPalette.Inactive,
                                                QPalette.WindowText, gray_text)
        self.orientation_label_palette.setBrush(QPalette.Disabled,
                                                QPalette.WindowText, gray_text)
        self.ortho_viewer_palette = QPalette()
        self.ortho_viewer_palette.setBrush(QPalette.Active, QPalette.Base,
                                           black_background)
        self.ortho_viewer_palette.setBrush(QPalette.Inactive, QPalette.Base,
                                           black_background)
        self.ortho_viewer_palette.setBrush(QPalette.Disabled, QPalette.Base,
                                           black_background)

        self.axialA_label.setPalette(self.orientation_label_palette)
        self.axialL_label.setPalette(self.orientation_label_palette)
        self.axialR_label.setPalette(self.orientation_label_palette)
        self.axialP_label.setPalette(self.orientation_label_palette)
        self.axial_view.setPalette(self.ortho_viewer_palette)
        self.sagittalS_label.setPalette(self.orientation_label_palette)
        self.sagittalA_label.setPalette(self.orientation_label_palette)
        self.sagittalI_label.setPalette(self.orientation_label_palette)
        self.sagittalP_label.setPalette(self.orientation_label_palette)
        self.sagittal_view.setPalette(self.ortho_viewer_palette)
        self.coronalL_label.setPalette(self.orientation_label_palette)
        self.coronalS_label.setPalette(self.orientation_label_palette)
        self.coronalR_label.setPalette(self.orientation_label_palette)
        self.coronalI_label.setPalette(self.orientation_label_palette)
        self.coronal_view.setPalette(self.ortho_viewer_palette)

    def set_gridlayouts(self):
        self.axial_gridLayout = QGridLayout()
        self.coronal_gridLayout = QGridLayout()
        self.sagittal_gridLayout = QGridLayout()
        self.imagecont_gridLayout = QGridLayout(self.slicecontrol_pane)
        self.imageframe_gridLayout = QGridLayout(self.imageframe)
        # self.graphcontrol_gridLayout = QGridLayout(self.graphcontrol_pane)
        self.verticalLayout = QVBoxLayout(self.controller_frame)
        self.horizontalLayout = QHBoxLayout(self.graph_frame)
        self.main_gridLayout = QGridLayout(self)
        # TODO: Will reactivate these on later version
        # self.imageframe_gridLayout.addWidget(self.axial_title, 0, 1, 1, 1)
        # self.imageframe_gridLayout.addWidget(self.coronal_title, 0, 2, 1, 1)
        # self.imageframe_gridLayout.addWidget(self.sagittal_title, 0, 0, 1, 1)
        # self.axial_gridLayout.addWidget(self.axialL_label, 1, 0, 1, 1)
        # self.axial_gridLayout.addWidget(self.axialA_label, 0, 1, 1, 1)
        # self.axial_gridLayout.addWidget(self.axialR_label, 1, 2, 1, 1)
        # self.axial_gridLayout.addWidget(self.axialP_label, 2, 1, 1, 1)
        self.axial_gridLayout.addWidget(self.axial_view, 1, 1, 1, 1)
        # self.sagittal_gridLayout.addWidget(self.sagittalS_label, 1, 0, 1, 1)
        # self.sagittal_gridLayout.addWidget(self.sagittalA_label, 0, 1, 1, 1)
        # self.sagittal_gridLayout.addWidget(self.sagittalI_label, 1, 2, 1, 1)
        # self.sagittal_gridLayout.addWidget(self.sagittalP_label, 2, 1, 1, 1)
        self.sagittal_gridLayout.addWidget(self.sagittal_view, 1, 1, 1, 1)
        # self.coronal_gridLayout.addWidget(self.coronalL_label, 1, 0, 1, 1)
        # self.coronal_gridLayout.addWidget(self.coronalS_label, 0, 1, 1, 1)
        # self.coronal_gridLayout.addWidget(self.coronalR_label, 1, 2, 1, 1)
        # self.coronal_gridLayout.addWidget(self.coronalI_label, 2, 1, 1, 1)
        self.coronal_gridLayout.addWidget(self.coronal_view, 1, 1, 1, 1)
        self.imagecont_gridLayout.addWidget(self.xaxis_label, 0, 0, 1, 1)
        self.imagecont_gridLayout.addWidget(self.xaxis_slider, 0, 1, 1, 1)
        self.imagecont_gridLayout.addWidget(self.xaxis_spinbox, 0, 2, 1, 1)
        self.imagecont_gridLayout.addWidget(self.yaxis_label, 1, 0, 1, 1)
        self.imagecont_gridLayout.addWidget(self.yaxis_slider, 1, 1, 1, 1)
        self.imagecont_gridLayout.addWidget(self.yaxis_spinbox, 1, 2, 1, 1)
        self.imagecont_gridLayout.addWidget(self.zaxis_label, 2, 0, 1, 1)
        self.imagecont_gridLayout.addWidget(self.zaxis_slider, 2, 1, 1, 1)
        self.imagecont_gridLayout.addWidget(self.zaxis_spinbox, 2, 2, 1, 1)
        self.imagecont_gridLayout.addWidget(self.frame_label, 3, 0, 1, 1)
        self.imagecont_gridLayout.addWidget(self.frame_slider, 3, 1, 1, 1)
        self.imagecont_gridLayout.addWidget(self.frame_spinbox, 3, 2, 1, 1)
        self.imageframe_gridLayout.addLayout(self.axial_gridLayout, 1, 1, 1, 1)
        self.imageframe_gridLayout.addLayout(self.coronal_gridLayout, 1, 2, 1,
                                             1)
        self.imageframe_gridLayout.addLayout(self.sagittal_gridLayout, 1, 0, 1,
                                             1)
        # self.graphcontrol_gridLayout.addWidget(self.addmask_button, 3, 0, 1, 1)
        # self.graphcontrol_gridLayout.addWidget(self.removemask_button, 3, 1, 1, 1)
        # self.graphcontrol_gridLayout.addWidget(self.mask_listview, 0, 0, 1, 5)
        # self.graphcontrol_gridLayout.addWidget(self.savepng_button, 3, 4, 1, 1)
        # self.graphcontrol_gridLayout.addWidget(self.savecsv_button, 3, 3, 1, 1)
        self.verticalLayout.addWidget(self.slicecontrol_pane)
        self.horizontalLayout.addWidget(self.graph_view)
        # self.horizontalLayout.addWidget(self.graphcontrol_pane)
        self.main_gridLayout.addWidget(self.imageframe, 0, 0, 1, 2)
        self.main_gridLayout.addWidget(self.controller_frame, 1, 0, 1, 1)
        self.main_gridLayout.addWidget(self.graph_frame, 1, 1, 1, 1)

    def set_objectnames(self):
        self.setObjectName(u"data_browser")
        self.imageframe.setObjectName(u"image_frame")
        self.axial_gridLayout.setObjectName(u"axial_gridLayout")
        self.coronal_gridLayout.setObjectName(u"coronal_gridLayout")
        self.sagittal_gridLayout.setObjectName(u"sagittal_gridLayout")
        # TODO: Will reactivate these on later version
        # self.axial_title.setObjectName(u"axial_label")
        # self.coronal_title.setObjectName(u"coronal_label")
        # self.sagittal_title.setObjectName(u"sagittal_label")
        self.axial_view.setObjectName(u"axial_view")
        self.sagittal_view.setObjectName(u"sagittal_view")
        self.coronal_view.setObjectName(u"coronal_view")
        # self.axialL_label.setObjectName(u"axialL_label")
        # self.axialR_label.setObjectName(u"axialR_label")
        # self.axialA_label.setObjectName(u"axialA_label")
        # self.axialP_label.setObjectName(u"axialP_label")
        # self.sagittalS_label.setObjectName(u"sagittalS_label")
        # self.sagittalA_label.setObjectName(u"sagittalA_label")
        # self.sagittalI_label.setObjectName(u"sagittalI_label")
        # self.sagittalP_label.setObjectName(u"sagittalP_label")
        # self.coronalL_label.setObjectName(u"coronalL_label")
        # self.coronalS_label.setObjectName(u"coronalS_label")
        # self.coronalR_label.setObjectName(u"coronalR_label")
        # self.coronalI_label.setObjectName(u"coronalI_label")
        self.controller_frame.setObjectName(u"controller_frame")
        self.slicecontrol_pane.setObjectName(u"slicecontrol_pane")
        self.xaxis_label.setObjectName(u"xaxis_label")
        self.xaxis_slider.setObjectName(u"xaxis_slider")
        self.xaxis_spinbox.setObjectName(u"xaxis_spinbox")
        self.yaxis_label.setObjectName(u"yaxis_label")
        self.yaxis_slider.setObjectName(u"yaxis_slider")
        self.yaxis_spinbox.setObjectName(u"yaxis_spinbox")
        self.zaxis_label.setObjectName(u"zaxis_label")
        self.zaxis_slider.setObjectName(u"zaxis_slider")
        self.zaxis_spinbox.setObjectName(u"zaxis_spinbox")
        self.frame_label.setObjectName(u"frame_label")
        self.frame_slider.setObjectName(u"frame_slider")
        self.frame_spinbox.setObjectName(u"frame_spinbox")
        self.graph_frame.setObjectName(u"graph_frame")
        self.graph_view.setObjectName(u"graph_view")
        # TODO: Will reactivate these on later version
        # self.graphcontrol_pane.setObjectName(u"graphcontrol_pane")
        # self.addmask_button.setObjectName(u"addmask_button")
        # self.removemask_button.setObjectName(u"removemask_button")
        # self.mask_listview.setObjectName(u"mask_listview")
        # self.savepng_button.setObjectName(u"savepng_button")
        # self.savecsv_button.setObjectName(u"savecsv_button")
        self.imagecont_gridLayout.setObjectName(u"imagecont_gridLayout")
        self.imageframe_gridLayout.setObjectName(u"imageframe_gridLayout")
        # self.graphcontrol_gridLayout.setObjectName(u"graphcontrol_gridLayout")
        self.verticalLayout.setObjectName(u"verticalLayout")
        self.horizontalLayout.setObjectName(u"horizontalLayout")
        self.main_gridLayout.setObjectName(u"main_gridLayout")
        QMetaObject.connectSlotsByName(self)

    def set_texts(self):
        self.setWindowTitle(u"Data Browser")
        # TODO: Will reactivate these on later version
        # self.axial_title.setText(u"**Axial**")
        # self.coronal_title.setText(u"**Coronal**")
        # self.sagittal_title.setText(u"**Sagittal**")
        # self.sagittalS_label.setText(u"**S**")
        # self.sagittalA_label.setText(u"**A**")
        # self.sagittalI_label.setText(u"**I**")
        # self.sagittalP_label.setText(u"**P**")
        # self.axialL_label.setText(u"**L**")
        # self.axialA_label.setText(u"**A**")
        # self.axialR_label.setText(u"**R**")
        # self.axialP_label.setText( u"**P**")
        # self.coronalL_label.setText(u"**L**")
        # self.coronalS_label.setText(u"**S**")
        # self.coronalR_label.setText(u"**R**")
        # self.coronalI_label.setText(u"**I**")
        self.slicecontrol_pane.setTitle(u"Slice Control Pane")
        self.xaxis_label.setText(u"x")
        self.yaxis_label.setText(u"y")
        self.zaxis_label.setText(u"z")
        self.frame_label.setText(u"Frame")
        # TODO: Will reactivate these on later version
        # self.graphcontrol_pane.setTitle(u"Graph Control Pane")
        # self.addmask_button.setText(u"+")
        # self.removemask_button.setText(u"-")
        # self.savepng_button.setText(u"toPNG")
        # self.savecsv_button.setText(u"toCSV")

    def plot_timecourse(self, x, y):
        self.graph_frame.setEnabled(True)
        self.graph_view.clear()
        pen = pg.mkPen(color=(255, 0, 0))
        if x is None:
            x = [0]
            y = [y]
            self.graph_view.plot(x, y, pen=pen, symbol='o')
        else:
            self.graph_view.plot(x, y, pen=pen)

    def get_coord(self):
        x = self.xaxis_slider.value()
        y = self.yaxis_slider.value()
        z = self.zaxis_slider.value()
        return (x, y, z)
Exemplo n.º 13
0
class Window_csv(QDialog):
    def __init__(self):
        #initialize from base class of Qdialog also with own __init__
        super().__init__()


        #window title
        self.setWindowTitle("Create from CSV")

        # intialized grid layout settings
        self.createGrid()
        vbox = QVBoxLayout()
        vbox.addWidget(self.groupBox)
        self.setLayout(vbox)

        #window title
        self.setWindowTitle("Create from CSV")

        #icon
        self.setIcon()

        # center, call last
        self.center()


    def createGrid(self):
        
        # top groupbox quote
        self.groupBox = QGroupBox("Make sure file is .csv")
        # font
        self.groupBox.setFont(QFont("Monospace",13))
        # initialize
        gridLayout = QGridLayout()

        # file path outward
        self.input_filepath_line = QLineEdit(self)
        self.input_filepath_label = QLabel(self)
        self.input_filepath_label.setText("Enter Destination Filepath: ")
        gridLayout.addWidget(self.input_filepath_line,3,1)
        gridLayout.addWidget(self.input_filepath_label,3,0)

        #check box
        self.check = QCheckBox("Yes", self)
        self.input_checkbox_label = QLabel(self)
        self.input_checkbox_label.setText("Headers on CSV?")
        self.check.stateChanged.connect(self.checkbox)
        self.check.toggle()
        gridLayout.addWidget(self.check,2,1)
        gridLayout.addWidget(self.input_checkbox_label,2,0)

        #file path inward
        self.input_ticker = QLineEdit(self)
        self.input_ticker_label = QLabel(self)
        self.input_ticker_label.setText("Enter Incoming Filepath: ")
        gridLayout.addWidget(self.input_ticker,1,1)
        gridLayout.addWidget(self.input_ticker_label,1,0)

        #search button, calls graph function from inputs
        search_Button = QPushButton("Graph", self)
        search_Button.setIcon(QIcon("search.png"))
        search_Button.setMinimumHeight(40)
        search_Button.clicked.connect(self.graph_csv)
        gridLayout.addWidget(search_Button, 4,1)

        #quit button calls quit function
        quit_Button = QPushButton("Quit", self)
        quit_Button.setIcon(QIcon("exit.png"))
        quit_Button.setMinimumHeight(40)
        quit_Button.clicked.connect(self.quitApp)
        gridLayout.addWidget(quit_Button, 4,0)

        # final for display and setting
        self.groupBox.setLayout(gridLayout)


    def checkbox(self,state):
        
        # check if checkbox is clicked
        if state == Qt.Checked:

            # create object to utilize in graphing functino (we need to know if it has headers)
            self.is_checked = True
        
        else:

            # create object to utilize in graphing functino (we need to know if it has headers)
            self.is_checked = False

    def graph_csv(self):
        
        # local copy of checked from previous object
        checked = self.is_checked

        # if checked is true
        if checked:
            
            # if this document has headers, try to let pandas infer them, and create the x,y graph then plot it 
            try:
                
                # read in the text from the checkbox
                csv = self.input_ticker.text()
                
                # utilize pandas to read in the dataframe
                csv_pd = pd.read_csv(csv, index_col=0)
                
                # check column length
                check_list = csv_pd.columns
                       
                # currently application is only useful for plotting two columns, if .column returns more than we won't be able to use it
                if len(check_list) > 2:
                    return "Please pass a file that isn't greater than two columns"

            except:
                # on error return that the file wasn't recongized and was unreadable
                return print("Incoming file path not recognized (possibly not a csv file?)")
        
        else:
            # this document doesn't have headers, create some false headers (so data isn't lost in intial row call these col1 and col2)
            try:
                
                # read in the text from the checkbox
                csv = self.input_ticker.text()

                # read in the dataframe, set the index to the first column.
                csv_pd = pd.read_csv(csv, names=["col1","col2"], index_col=0)
                
                # get a list of the column for check
                check_list = csv_pd.columns
                
                # currently application is only useful for plotting two rows, if .column returns more than we won't be able to use it
                if len(check_list) > 2:
                    return "Please pass a file that isn't greater than two columns"
            
            except:
                # on error return that the file wasn't recongized and was unreadable
                return print("Incoming file path not recognized (possibly not a csv file?) or header error")


        # initialize a figure
        p = figure(width=500,height=250)

        #table formatting
        p.title.text = "My Graph"
        p.title.align = "right"
        p.title.text_color = "navy"
        p.title.text_font_size = "25px"


        #plot the values, use the index and the first col
        p.line(csv_pd.index, csv_pd.iloc[:,0], color="Navy", line_width=2, alpha=0.5)

        # name file, will do basedir if not specified
        if not self.input_filepath_line.text():
            print("This will push a file to the base directory")
        else:
            #destination file path with My_Graph.html name
            file_attempt = str(self.input_filepath_line.text() + "/" + "My_Graph.html")

        # try to push the file to the name described, if not go base dir instead
        try:
            output_file(file_attempt)
            print('File saved to: ' + file_attempt)
        except:
            print('Please fix or add a the directory, pushed to local dir')

        # show the figure
        show(p)

    # set the icon of the gui app
    def setIcon(self):
        appIcon = QIcon("csv.png")
        self.setWindowIcon(appIcon)

    # center the applciation in the middle of the screen
    def center(self):
        # create frame of screen
        qRect = self.frameGeometry()
        # find the center point
        centerPoint = QDesktopWidget().availableGeometry().center()
        # moveCenter to the center point
        qRect.moveCenter(centerPoint)
        # from the top left??
        self.move(qRect.topLeft())

    # quit when called
    def quitApp(self):
        userInfo = QMessageBox.question(self, "Confirmation", "Leave the application?",
            QMessageBox.Yes | QMessageBox.No)

        if userInfo == QMessageBox.Yes:
            myApp.quit()
        else:
            pass
Exemplo n.º 14
0
class Window(QWidget):
    def __init__(self):
        
        #initialize base class
        super().__init__()

        # set the window title
        self.setWindowTitle("Build Interactive Charts")

        #use this to create a grid layout
        self.createGrid()
        vbox = QVBoxLayout()
        vbox.addWidget(self.groupBox)
        self.setLayout(vbox)

        # set the icon for taskbar and the top left
        self.setIcon() 

        # center the widget
        self.center()

    # set the icon from a pictures
    def setIcon(self):
        appIcon = QIcon("stock.png")
        self.setWindowIcon(appIcon)

    # center the gui app in the middle of the screen
    def center(self):
        
        # create frame of screen
        qRect = self.frameGeometry()
        # find the center point
        centerPoint = QDesktopWidget().availableGeometry().center()
        # moveCenter to the center point
        qRect.moveCenter(centerPoint)
        # from the top left??
        self.move(qRect.topLeft())

    # create the layout of the gui on the screen
    def createGrid(self):
        
        # top groupbox quote
        self.groupBox = QGroupBox("Search a Stock ------> Downloadable Interactive Chart")
        # font
        self.groupBox.setFont(QFont("Monospace",13))
        # initialize
        gridLayout = QGridLayout()

        # send call to func from search button
        new_gui = QPushButton("Graph CSV", self)
        new_gui.setIcon(QIcon("csv.png"))
        new_gui.setMinimumHeight(10)
        new_gui.clicked.connect(self.new_GUI_link)
        gridLayout.addWidget(new_gui, 0,1)

        #input own data
        self.input_owndata_label = QLabel(self)
        self.input_owndata_label.setText("Input own data: ")
        gridLayout.addWidget(self.input_owndata_label,0,0)

        #input exit destination file path
        self.input_filepath_line = QLineEdit(self)
        self.input_filepath_label = QLabel(self)
        self.input_filepath_label.setText("Enter Destination File Path: ")
        gridLayout.addWidget(self.input_filepath_line,2,1)
        gridLayout.addWidget(self.input_filepath_label,2,0)

        #input text for ticker
        self.input_ticker = QLineEdit(self)
        self.input_ticker_label = QLabel(self)
        self.input_ticker_label.setText("Input Ticker to search: ")
        gridLayout.addWidget(self.input_ticker,1,1)
        gridLayout.addWidget(self.input_ticker_label,1,0)

        # search button
        search_Button = QPushButton("Search", self)
        search_Button.setIcon(QIcon("search.png"))
        search_Button.setMinimumHeight(40)
        search_Button.clicked.connect(self.get_Ticker)
        gridLayout.addWidget(search_Button, 4,1)

        #quit button
        quit_Button = QPushButton("Quit", self)
        quit_Button.setIcon(QIcon("exit.png"))
        quit_Button.setMinimumHeight(40)
        quit_Button.clicked.connect(self.quitApp)
        gridLayout.addWidget(quit_Button, 4,0)

        # set the layout once called 
        self.groupBox.setLayout(gridLayout)

    #quit app when called
    def quitApp(self):

        #Yes or No check box for quitting
        userInfo = QMessageBox.question(self, "Confirmation", "Leave the application?",
            QMessageBox.Yes | QMessageBox.No)

        # if yes quit
        if userInfo == QMessageBox.Yes:
            myApp.quit()

    # get ticker information, and graph
    def get_Ticker(self):

        # create start and end times (5 years)
        today = date.today()
        start = datetime.datetime(today.year-5, today.month, today.day)
        end = datetime.datetime(today.year, today.month, today.day)

        # create local variable from class obj
        ticker_name = self.input_ticker.text()

        # DataReader to pull from yahoo source
        try:
            df = data.DataReader(name=ticker_name,data_source="yahoo",start=start,end=end)
        except:
            return print('Ticker not available')

        # create the figure (sizing_mode='scale_width' makes it take up the whole page)
        p = figure(width=500,height=250,x_axis_type="datetime")

        # table formatting, use ticker name as title
        p.title.text = ticker_name
        p.title.align = "right"
        p.title.text_color = "navy"
        p.title.text_font_size = "25px"

        # create line chart, utilizing the close col from the API
        p.line(df.index, df["Close"], color="Navy", line_width=2, alpha=0.5)

        # name file, will do basedir if not specified
        if not self.input_filepath_line.text():
            print("This will push a file to the base directory")
        else:
            #push file, utilize the ticker name and the destination filepath
            file_attempt = str(self.input_filepath_line.text() + "/" + ticker_name + ".html")

        try:
            output_file(file_attempt)
            print('File saved to: ' + file_attempt)
        except:
            print('Please fix the directory')

        # show the figure
        show(p)


    def new_GUI_link(self):

        # initialize second window
        second_window = Window_csv()

        # recolor
        p = QPalette()
        p.setColor(QPalette.Background, QColor("white"))
        second_window.setPalette(p)
        
        #show and exec (on click)
        second_window.show()
        second_window.exec_()
Exemplo n.º 15
0
class Window(QWidget):
    def __init__(self):
        super().__init__()

        self.cached_dirs = []
        self.path = 'F:\\browser-test\\test-dir'
        self.image_path = ''
        if platform.system() == 'Windows':
            self.drives = [
                '%s:\\' % d for d in string.ascii_uppercase
                if os.path.exists('%s:\\' % d)
            ]
        else:
            self.drives = []

        self.setWindowTitle('file-browser')
        self.setGeometry(200, 200, 800, 600)

        self.create_layout()
        self.image_button = QPushButton('image-viewer', self)

        vbox = QVBoxLayout()
        vbox.addWidget(self.group)
        vbox.addWidget(self.image_button)

        self.image_window = None
        self.image_button.clicked.connect(self.launch_image_window)

        self.setLayout(vbox)
        self.mid_list.setFocus()

        self.show()

    def closeEvent(self, event):
        '''Additionally close the secondary windows on close.'''
        try:
            self.image_window.close()
        except:
            pass
        return super().closeEvent(event)

    def create_layout(self):
        '''Draw a frame* with current directory on top and 2* lists inside.'''
        self.group = QGroupBox(self.cut_string(self.path))
        self.group.setFont(QFont('Sanserif', 14))

        hbox = QHBoxLayout()

        try:
            self.left_list = self.create_file_list(
                os.path.abspath(os.path.join(self.path, '..')),
                os.path.basename(self.path), True)
        except Exception as e:
            self.left_list = self.create_file_list('')
            print(e)
            traceback.print_tb(e.__traceback__)
        self.left_list.setMinimumSize(self.width() / 3, 300)
        hbox.addWidget(self.left_list)

        try:
            self.mid_list = self.create_file_list(self.path)
        except Exception as e:
            print(e)
            traceback.print_tb(e.__traceback__)
        self.mid_list.setMinimumSize(self.width() / 3, 300)
        hbox.addWidget(self.mid_list)

        # FIXME: label's place gets filled by others when in a different window size
        self.right_panel = QLabel()
        self.right_panel.setMinimumSize(self.width() / 3, 300)
        picture = QPixmap('F:\\browser-test\\test-dir\\4.jpg')
        # FIXME: reset on resize
        picture = picture.scaled(int(self.width() / 3), int(self.height() / 3),
                                 QtCore.Qt.KeepAspectRatio)
        self.right_panel.setPixmap(picture)
        hbox.addWidget(self.right_panel)

        self.left_list.itemDoubleClicked.connect(self.item_click)
        self.mid_list.itemDoubleClicked.connect(self.item_click)

        self.group.setLayout(hbox)

    def keyPressEvent(self, event):
        print('key press')
        # FIXME: doesn't register q key at launch, only works after opening the secondary window
        if event.key() == QtCore.Qt.Key_Q:
            print('q press')
            self.close()
        elif event.key() == QtCore.Qt.Key_Left:
            print('left key')
            # FIXME: requires double left click for whatever reason
            self.item_click(self.left_list.item(0))
        elif event.key() == QtCore.Qt.Key_Right or event.key(
        ) == QtCore.Qt.Key_Return or event.key() == QtCore.Qt.Key_Enter:
            print('right key or enter')
        return super().keyPressEvent(event)

    def item_click(self, item):
        '''Navigate to a new directory when clicked on a list.
		
		item -- clicked QListWidgetItem
		'''
        print(item, str(item.text()), str(mimetypes.guess_type(item.text())))
        print(mimetypes.guess_type(item.text())[0])
        # TODO: probably use a better method
        if str(item.text()) == '((empty))' or str(item.text()) == '((root))':
            return

        # TODO: possibly display preview on one click and open the image in preferred image software on double.
        # TODO: maybe only proceed to a directory if mimetype guess is None? though suppose it could also display None for no extension files
        # and inversely may read directories with extension-like names as those type
        guess = mimetypes.guess_type(item.text())[0]
        if guess:  # if not None, e.g. directory
            if 'image' in mimetypes.guess_type(item.text())[0]:
                if item.listWidget() == self.mid_list:
                    self.image_path = self.path
                elif item.listWidget() == self.left_list:
                    # TODO: likely navigate one level above if it's on the left list
                    self.image_path = os.path.abspath(
                        os.path.join(self.path, '..'))
                self.image_path = os.path.join(self.image_path,
                                               str(item.text()))
                picture = QPixmap(self.image_path)
                picture = picture.scaledToWidth(int(self.width() / 3))
                self.right_panel.setPixmap(picture)
                return

        self.right_panel.setPixmap(QPixmap())

        path = self.path
        if item.listWidget() == self.mid_list:
            path = os.path.join(path, str(item.text()))
        elif item.listWidget() == self.left_list:
            if item.text() == '..':
                add = ''
            else:
                add = str(item.text())
            path = os.path.abspath(os.path.join(path, '..', add))
        self.path = path
        self.group.setTitle(self.cut_string(path))
        self.update_file_lists(path)

    def update_file_lists(self, path):
        '''Re-populate file lists with given new path.
		
		path -- new path to get items of the lists
		'''
        left_path = os.path.abspath(os.path.join(path, '..'))
        up_check = False if left_path == path else True
        try:
            if up_check:
                self.create_file_list(left_path, os.path.basename(path),
                                      up_check, self.left_list)
            else:
                self.create_file_list('', update_list=self.left_list)
        except Exception as e:
            print(e)
            traceback.print_tb(e.__traceback__)
        self.create_file_list(path, update_list=self.mid_list)

    def create_file_list(self,
                         path,
                         selected=None,
                         up=False,
                         update_list=None):
        '''Return a file list with objects populated from files/dirs in given path.

		path -- path of directory to create list elements
		selected -- name of the cwd to select in parent list
		up -- create a link to one level up
		update_list -- (QListWidget) update the given list with new path elements rather than returning a new list
		'''
        if not update_list:
            file_list = QListWidget(self)
        else:
            update_list.clear()
            file_list = update_list

        if not path and not update_list:  # if empty
            return file_list
        elif not path and update_list:
            if len(self.drives) > 0:
                for letter in self.drives:
                    try:
                        icon = QIcon(convert_to_icon(letter))
                    except Exception as e:
                        print(e)
                        traceback.print_tb(e.__traceback__)
                    update_list.addItem(QListWidgetItem(icon, letter))
            else:
                update_list.addItem(QListWidgetItem('((root))'))
            return

        # cache read contents of path to save some time and processing power?
        # TODO: could maybe also save actual QListWIdgetItems? to save on Icon creation time
        # could also copy QIcons to cached_dirs = {... 'dir_icons': [], 'file_icons': []}
        if not any(c['path'] == path for c in self.cached_dirs):
            files, dirs, dirpath = get_files(path)
            cache = {
                'path': dirpath,
                'dirs': dirs.copy(),
                'files': files.copy()
            }
            self.cached_dirs.append(cache)
            # dirs cache limit
            if len(self.cached_dirs) > 15:
                del self.cached_dirs[0]
        else:
            for c in self.cached_dirs:
                if c['path'] == path:
                    files, dirs, dirpath = c['files'].copy(), c['dirs'].copy(
                    ), c['path']

        if up:
            dirs.insert(0, os.path.abspath(os.path.join(path)))

        selected_index = -1
        if len(files) > 0:
            for i in range(len(files)):
                try:
                    icon = QIcon(
                        convert_to_icon(os.path.join(dirpath, files[i])))
                except Exception as e:
                    print(e)
                    traceback.print_tb(e.__traceback__)
                    icon = QIcon()
                files[i] = QListWidgetItem(icon, files[i])
        if len(dirs) > 0:
            for i in range(len(dirs)):
                if dirs[i] == selected:
                    selected_index = i
                try:
                    icon = QIcon(
                        convert_to_icon(
                            os.path.abspath(os.path.join(dirpath, dirs[i]))))
                except Exception as e:
                    print(e)
                    traceback.print_tb(e.__traceback__)
                    icon = QIcon()
                dirs[i] = QListWidgetItem(icon, dirs[i])

        if up:
            dirs[0].setText('..')

        if len(dirs) > 0:
            for d in dirs:
                file_list.addItem(d)
        if len(files) > 0:
            for f in files:
                file_list.addItem(f)

        if len(dirs) == 0 and len(files) == 0:
            file_list.addItem(QListWidgetItem('((empty))'))

        if selected_index >= 0:
            file_list.item(selected_index).setSelected(True)
            file_list.scrollToItem(file_list.item(selected_index))
        else:
            file_list.item(0).setSelected(True)

        if update_list:
            return
        return file_list

    def cut_string(self, s):
        '''Cut frame* title string so it fits the window.
		
		s -- path string that gets cut and added leading ellipsis'''
        limit = int(self.width() / 10)
        if len(s) > limit:
            s = '...' + s[len(s) - limit:]
        return s

    def launch_image_window(self):
        '''Launch secondary image viewing window.'''
        print(self.image_window)
        if 'self.image_window' in globals():
            self.image_window.show()
        else:
            self.image_window = image_viewer.Window()
            print(self.image_window)
        if self.image_path:
            self.image_window.set_image(self.image_path)
Exemplo n.º 16
0
class GUI(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Plotting Functions")
        self.setGeometry(400,400,400,400)
        self.setMinimumHeight(200)
        self.setMinimumWidth(200)
        self.setMaximumHeight(600)
        self.setMaximumWidth(800)
        self.equation_line_edit = QLineEdit()
        self.minimum_line_edit = QLineEdit()
        self.maximum_line_edit = QLineEdit()
        self.icon()
        self.centering_window()
        self.layout()
        vbox=QVBoxLayout()
        vbox.addWidget(self.group_message)
        self.setLayout(vbox)
    def icon(self):
        window_icon=QIcon("icon.png")  # object for QICon
        self.setWindowIcon(window_icon)  # Passing the QICon object to setWindowIcon to display it when running the code
    def centering_window(self):
        center=self.frameGeometry()
        center_point=QDesktopWidget().availableGeometry().center()
        center.moveCenter(center_point)
        self.move(center.topLeft())
    def layout(self):
        self.group_message= QGroupBox("Please fill the following spaces")  # Object for GroupBox
        self.group_message.setFont(QFont("Decorative", 14))
        grid_layout=QGridLayout()  #object for QGrid Layout
        button1 = QPushButton("Equation", self)
        grid_layout.addWidget(button1,0,0)  # Button1 is a widget which will be put in the 0 row and 0 column
        grid_layout.addWidget(self.equation_line_edit,0,1)
        button2=QPushButton("Minimum Values of x", self)
        grid_layout.addWidget(button2,1,0)
        #minimum_line_edit.setValidator(QDoubleValidator())                 #PyQt minimum_line_edit.setValidator(QIntValidator)
        grid_layout.addWidget(self.minimum_line_edit, 1, 1)
        button3 = QPushButton("Maximum vales of x", self)
        grid_layout.addWidget(button3,2,0)
        #maximum_line_edit.setValidator(QDoubleValidator())
        grid_layout.addWidget(self.maximum_line_edit,2,1)
        button4 = QPushButton("Setting Values", self)
        button4.clicked.connect(self.setting_values)
        grid_layout.addWidget(button4,3,0)
        button5 = QPushButton("PLot", self)
        button5.clicked.connect(self.message_box)
        grid_layout.addWidget(button5,3,1)
        self.group_message.setLayout(grid_layout)
    def setting_values(self):
        equation = self.equation_line_edit.text()
        mini = int(self.minimum_line_edit.text())
        maxi = int(self.maximum_line_edit.text())
    def equation_data(self):
        return self.equation_line_edit.text()
    def minimum_data(self):
        return int(self.minimum_line_edit.text())
    def maximum_data(self):
        return int(self.maximum_line_edit.text())

    def validations(self):
        equation = GUI.equation_data()
        global total_size_cap
        global array_of_plus
        global total_size_multipliers
        global wrong_sign
        global power
        global powers
        global coefficients
        global equal_sign
        global division
        global array_of_multipliers
        global total_size_multipliers
        list_of_coefficients = []
        division = 0
        array_index_absolute_values = []
        array1 = []
        array2 = []
        q = 0
        m = 0
        sign = 0
        array_of_multipliers = []
        equal_sign = 0
        total_size_multipliers = 0
        total_size_cap = 0
        array_of_caps = []
        array_of_plus = []
        coefficients = []
        array_of_coefficients = []
        array_absolute_values = []
        total_cap = 0
        extra_sign = 0
        power = 0
        powers = []
        num_of_multipliers = 0
        wrong_sign = 0
        list_of_strings = []
        for i in range(len(equation)):
            u = i
            if (equation[i] == '*' or equation[i] == '/') and equation[i + 1] == 'x':
                t = 0
                while t < u:
                    array_absolute_values.append(equation[t])
                    t += 1
                    if equation[t] == '+' or equation[t] == '-':
                        if equation[t - 1] == '^':
                            # as if the power has a sign +ve or negative i will not take that sign into consideration
                            continue
                        array_index_absolute_values.append(
                            equation.index(array_absolute_values[len(array_absolute_values) - 1]))
                        # As if there is any absolute value in the middle term, before '*' or '/' sign there will be 2 plus sign if i assign the index of each one into list and make while loop i will append the value between two plus sign and this will be the coefficient
                        del array_absolute_values[:]
                        n = array_index_absolute_values[len(array_index_absolute_values) - 2] + 1
                        b = array_index_absolute_values[len(array_index_absolute_values) - 1] + 1
                        # i added 1 to n and b as i check for equation of t after adding 1 to (t) so if the equation is 3*x^2+5+4*x, i will get the index of 2 and 5 but i want the index of '+' sign so i added 1
                        while n < b:
                            array_absolute_values.append(equation[n])
                            # adding the values between the two plus signs to lis then adding it as string and at the end converting it into float
                            n += 1
                            if equation[n] == 'x':
                                del array_absolute_values[:]
                                break
                        summation_absolute_values = ''
                        for s in range(len(array_absolute_values)):
                            summation_absolute_values = summation_absolute_values + array_absolute_values[s]
                        if summation_absolute_values == '':
                            continue
                        del array_absolute_values[:]
                        coefficients.append(summation_absolute_values)
                        total_cap = +1  # To add 1 cap as i compare number of caps to number of pluses
                array_of_multipliers.append(equation[i])
                last_slash = 0
                sign = 0
                r = 0
                number_of_slash = 0
                while r < u:
                    if last_slash == 1:
                        break
                    list_of_coefficients.append(equation[r])
                    r += 1
                    if equation[i - r] == '/' and equation[i - r + 1] != 'x':
                        sign += 1  # indicates that what before '*' or '/' was assigned as coefficient to coefficients and prevent taking what before '*' as coefficient again
                        del list_of_coefficients[:]
                        v = 0
                        # number_of_slash+=1
                        while v < i - r:
                            list_of_coefficients.append(equation[
                                                            v])  # as if there is fraction before multiplier or divider i will take the value before '/' sign and put it into array and then take the float of this array
                            v += 1
                            if equation[v] == '+' or equation[v] == '-':
                                del list_of_coefficients[
                                    :]  # as if the fraction came in any term '/' sign will have '+' or '-' before it so i delete all the values before '+' or '-'
                        last_slash += 1  # as the last slash will be came first as i check for i-r not r and if there is more than 1 one slash, i want the last one only
                        array_before_sign = ''
                        for g in range(len(list_of_coefficients)):
                            array_before_sign = array_before_sign + list_of_coefficients[g]
                        if array_before_sign == '':
                            continue
                        array1.append(float(array_before_sign))
                        del list_of_coefficients[:]
                        index = equation.index(equation[i - r])
                        while index < i:
                            list_of_coefficients.append(equation[
                                                            index])  # as equation.index(equation[i-r]) will give me the index of '/' sign then adding what after it into array and converting it into float
                            index += 1
                            if equation[index] == '/':
                                del list_of_coefficients[:]

                        list_of_coefficients.pop(0)  # as the first element will be '/' sign
                        array_after_sign = ''
                        for k in range(len(list_of_coefficients)):
                            array_after_sign = array_after_sign + list_of_coefficients[k]
                        j = 0
                        while j < i:
                            if equation[j] == '/' and equation[j + 1] != 'x':
                                number_of_slash += 1
                            j += 1
                        if number_of_slash == len(array_of_multipliers):
                            array2.append(float(array_after_sign))
                        elif number_of_slash == len(array_of_multipliers) - 1:
                            sign = 0
                            continue
                        del list_of_coefficients[:]
                        coefficients.append(str(array1[0] / array2[0]))
                        del array1[:]
                        del array2[:]

                p = 0
                while p < u:
                    array_of_coefficients.append(equation[p])
                    p += 1
                    if equation[p] == '+' or equation[
                        p] == '-':  # to remove the elements before '+' or '-' as the second term coefficient will be lied betweem '+' and '*'
                        del array_of_coefficients[:]
                summation_of_coefficients = ''
                for o in range(len(array_of_coefficients)):
                    summation_of_coefficients = summation_of_coefficients + array_of_coefficients[o]
                del array_of_coefficients[:]
                if sign != 0:
                    continue
                else:
                    coefficients.append(summation_of_coefficients)
                    # if equation[i]== '/' and equation[i+1] != 'x':
                    # extra_sign+=1
            if equation[i] == '^':
                array_of_caps.append(equation[i])
                if equation[i - 1] == equation[0]:  # input: x^2+..
                    num_of_multipliers += 1  # as i plot by comparing number of multipliers and caps to number of plus
                    coefficients.append('1')
                elif equation[i - 2] == equation[0]:  # input: -x^2+..
                    num_of_multipliers += 1
                    coefficients.append('-1')
                elif equation[i - 3] == '/':  # input: 5/2x^2+..
                    extra_sign += 1
            if equation[i] == '\\':  # input: 5\2*x^2+..
                wrong_sign += 1
            if equation[i] == '+' or equation[i] == '-':
                if equation[i] == equation[0]:
                    continue
                if equation[i - 1] == '^':  # 3*x^-2+5*x^1+5
                    continue
                array_of_plus.append(equation[i])
                p = 0
                while p < u:
                    list_of_strings.append(equation[p])
                    p += 1
                    if equation[i - 1] == 'x':  # in case of the input is 4*x^2+3*x+5 or 4*x^2+x+5
                        m = m - 1
                        del list_of_strings[:]
                        list_of_strings.append('1')
                        continue
                    if (equation[p + 1] == '+' or equation[p + 1] == '-') and equation[p] == '^':
                        m = m - 1
                        # as if the power is +ve or negative i neglect that sign in my calculation
                        # continue
                    if equation[p + 1] == '+' or equation[p + 1] == '-':
                        m += 1
                    if equation[p] == '^':
                        m = m - 1
                        q += 1
                        del list_of_strings[:]
                        continue
                    if equation[p] == equation[0] == '+' or equation[p] == equation[0] == '-':
                        m = m - 1
                    if equation[p] == 'x' and (equation[p + 1] == '+' or equation[p + 1] == '-') and equation[i] != '+':
                        m = m - 1
                if q >= 1:
                    list_of_strings.pop(0)
                if m > 0:  # as if there is absolute value between two terms the power of that term should be equal zero, m=2 for 2 plus sign and m=1 for 1 cap so the power of that term = 0
                    del list_of_strings[:]
                    list_of_strings.append('0')
                summation_of_powers = ''
                for w in range(len(list_of_strings)):
                    summation_of_powers = summation_of_powers + list_of_strings[w]
                del list_of_strings[:]
                powers.append(summation_of_powers)
                q = 0
                m = 0
                if equation[i - 1] == equation[0] == 'x':  # input: x+..
                    num_of_multipliers += 1
                    total_cap += 1
                    coefficients.append('1')
                elif equation[i - 2] == equation[0] == '-':  # input: -x+..
                    num_of_multipliers += 1
                    total_cap += 1
                    coefficients.append('-1')
                elif equation[i - 2] == '+' and equation[i - 1] == 'x':  # input: +x+...
                    num_of_multipliers += 1
                    total_cap += 1
                    coefficients.append('1')
                elif equation[i - 2] == '-' and equation[i - 1] == 'x':  # input: -x+
                    num_of_multipliers += 1
                    total_cap += 1
                    coefficients.append('-1')
                elif equation[i - 2] == '*' or equation[i - 2] == '/':  # input: +3*x+..
                    total_cap += 1
                elif equation[i - 3] == '+' or equation[i - 3] == '-':  # input: +3x+
                    total_cap += 1
            if equation[i] == '=':
                equal_sign += 1
        n = 1
        while n < len(equation):
            array_of_coefficients.append(equation[len(equation) - n])
            list_of_strings.append(
                equation[len(equation) - n])  # as if the last term is x^2 i take 2 as power of last term
            n += 1
            if equation[len(equation) - n] == '=':
                break
            if equation[len(equation) - n] == '^':  # in case the input is in the form of: 5*x^5+4*x+5*x^0
                list_of_strings.reverse()
                summation_power_last_term = ''
                for w in range(len(list_of_strings)):
                    summation_power_last_term = summation_power_last_term + list_of_strings[w]
                del list_of_strings[:]
                powers.append(summation_power_last_term)
                # total_cap=total_cap-1
                del array_of_coefficients[:]
                break
            if equation[len(equation) - n] == '*' or equation[
                        len(equation) - n] == '/':  # in case the input is in the form of: 5*x^2+4*x
                # extra_sign+=1
                powers.append('1')
                del array_of_coefficients[:]
                break
            if equation[len(equation) - n] == '+' or equation[
                        len(equation) - n] == '-':  # to get the coefficients of last term: 5*x^2+4*x(+10.3)
                array_of_coefficients.append(equation[len(equation) - n])
                array_of_coefficients.reverse()  # as the list will be reversed; e.g. ['0' , '1' , '+' ] as the last element will be put first so i reversed it in order to manage to add elements
                summation_last_term = ''
                for e in range(len(array_of_coefficients)):
                    summation_last_term = summation_last_term + array_of_coefficients[e]
                del array_of_coefficients[:]
                # summation_last_term
                coefficients.append(summation_last_term)
                if equation[len(equation) - (
                    n + 1)] == '^':  # in case of the input is 3*x+4+5*x^-2, don't take the coefficient if equation[len(equation) - (n+1) ] == '^'
                    coefficients.pop()
                    list_of_strings.append(equation[len(equation) - n])  # to take a sign with the power
                    list_of_strings.reverse()
                    summation_power_last_term = ''
                    for w in range(len(list_of_strings)):
                        summation_power_last_term = summation_power_last_term + list_of_strings[w]
                    del list_of_strings[:]
                    powers.append(summation_power_last_term)
                break

        if equation[len(equation) - 2] == equation[1] == '^':  # input: x^2
            total_cap = total_cap - 1
            # coefficients.append('1')
        if equation[len(equation) - 2] == equation[2] == '^':  # input: -x^2
            total_cap = total_cap - 1
            # coefficients.append('-1')
        total_size_multipliers = len(array_of_multipliers) + num_of_multipliers - extra_sign - wrong_sign
        total_size_cap = len(array_of_caps) + total_cap
        # if equation[len(equation) - 2] == '^' and (equation[len(equation) - 4] == '*' or equation[len(equation) - 4] == '/'):  # input: 5*x^2+3*x+4*x^0
        # total_size_multipliers = total_size_multipliers - 1

    def plot(self):
        GUI.validations()
        global complex_value
        complex_value = 0
        global y
        global sum_of_coefficients
        global x
        y = []
        sum_of_coefficients = []
        mini = GUI.minimum_data()
        maxi = GUI.maximum_data()
        x = list(range(mini, maxi + 1))
        q = 0
        multipliers = array_of_multipliers
        if len(coefficients) > len(multipliers):
            difference = len(coefficients) - len(multipliers)
            c = 0
            while c < difference:
                multipliers.append("")
                c += 1
        # as i will check for array_of_multipliers[i] and inrease it by 1 like j but array of coefficients is more 1 element than array_of_multipliers, so if i dont't add one element to that array i will exceed the index
        while q < len(x):
            j = 0
            i = 0
            # b = list_of_strings
            b = powers
            if len(coefficients) > len(
                    b):  # to make list_of_strings of the same length of coefficients, so if the difference between them is one so zero is added to list_of_strings
                difference_of_lengths = len(coefficients) - len(b)
                k = 0
                while k < difference_of_lengths:
                    b.extend('0')
                    k += 1
            while j < len(coefficients):
                if multipliers[i] == '/':
                    y.append(float(coefficients[j]) / x[q] ** float(b[j]))
                else:
                    y.append(float(coefficients[j]) * x[q] ** float(b[j]))
                i += 1
                j += 1
            summation = 0
            for u in range(len(y)):
                summation = summation + y[u]
            del y[:]
            sum_of_coefficients.append(summation)
            q = q + 1
            # array_of_multipliers.pop() # to erase the addedd element to the list

    def message_box(self):
        GUI.validations()
        GUI.plot()
        if equal_sign != 0:
            QMessageBox.warning(self, "Warning","You Can't use equal sign, The equation should be in that form: 5*x^2+3*x+5")
        if wrong_sign != 0:
            QMessageBox.warning(self, "Warning", "You have to use '/' as a division sign")
        if total_size_cap < len(array_of_plus):
            QMessageBox.warning(self, "Warning", "You have to use '^' as a power sign")
        if total_size_multipliers < len(array_of_plus):
            QMessageBox.warning(self, "Warning", "You have to write '*' or '/'; e.g. 5*x^2")
        if total_size_cap == len(array_of_plus) and total_size_multipliers == len(array_of_plus) and wrong_sign == 0 and equal_sign == 0:
            plt.plot(x, sum_of_coefficients, label='Quadratic')
            plt.show()
Exemplo n.º 17
0
class GeneratorPanel(QWidget):
    def __init__(self, npc_generator: NPCGenerator, parent=None):
        super(GeneratorPanel, self).__init__(parent)
        self.parent = parent
        self.npc = npc_generator
        self.layout = QVBoxLayout()

        self.tool_tip = ConfigParser()
        self.tool_tip.read("descriptions.ini", "utf-8")

        self.gender = ""
        self.last_job = ""

        self.tag_line = QHBoxLayout()
        self.tag_line.addWidget(QLabel("Tags :"))
        self.tags = QLineEdit()
        self.tag_line.addWidget(self.tags)
        self.search_tags = QPushButton("Ajouter des tags...")
        self.search_tags.clicked.connect(lambda: self.tags_selection())
        self.tag_line.addWidget(self.search_tags)
        self.layout.addLayout(self.tag_line)

        self.line_layout = QHBoxLayout()
        npc_font = QFont()
        npc_font.setPointSize(15)
        self.name_label = QLineEdit()
        self.name_label.textChanged.connect(self.set_tab_name)
        self.name_label.setFont(npc_font)
        self.line_layout.addWidget(self.name_label)
        verb_label = QLabel("est")
        verb_label.setFont(npc_font)
        self.line_layout.addWidget(verb_label)
        self.job_label = QLineEdit()
        self.job_label.setFixedWidth(230)
        self.job_label.setFont(npc_font)
        self.line_layout.addWidget(self.job_label)
        self.specie_label = QLineEdit()
        self.specie_label.setFixedWidth(130)
        self.specie_label.setFont(npc_font)
        self.line_layout.addWidget(self.specie_label)
        appearance_label = QLabel("plutôt")
        appearance_label.setFont(npc_font)
        self.line_layout.addWidget(appearance_label)
        self.appearance_label = QLineEdit()
        self.appearance_label.setFixedWidth(130)
        self.appearance_label.setFont(npc_font)
        self.line_layout.addWidget(self.appearance_label)
        comma_label = QLabel(',')
        comma_label.setFont(npc_font)
        self.line_layout.addWidget(comma_label)
        self.behavior_label = QLineEdit()
        self.behavior_label.setFixedWidth(235)
        self.behavior_label.setFont(npc_font)
        self.line_layout.addWidget(self.behavior_label)
        personality_label = QLabel(", semble être")
        personality_label.setFont(npc_font)
        self.line_layout.addWidget(personality_label)
        self.personality_label = QLineEdit()
        self.personality_label.setFixedWidth(175)
        self.personality_label.setFont(npc_font)
        self.line_layout.addWidget(self.personality_label)
        accessories_label = QLabel("et a")
        accessories_label.setFont(npc_font)
        self.line_layout.addWidget(accessories_label)
        self.accessories_label = QLineEdit()
        self.accessories_label.setFont(npc_font)
        self.line_layout.addWidget(self.accessories_label)
        self.layout.addLayout(self.line_layout)

        self.fix_line = QHBoxLayout()
        self.fixes = list()
        self.fix_name = QCheckBox("fixer nom")
        self.fixes.append(self.fix_name)
        self.fix_line.addWidget(self.fix_name)

        self.fix_job = QCheckBox("fixer métier")
        self.fixes.append(self.fix_job)
        self.fix_line.addWidget(self.fix_job)

        self.fix_specie = QCheckBox("fixer espèce")
        self.fixes.append(self.fix_specie)
        self.fix_line.addWidget(self.fix_specie)

        self.fix_appearance = QCheckBox("fixer apparence")
        self.fixes.append(self.fix_appearance)
        self.fix_line.addWidget(self.fix_appearance)

        self.fix_behavior = QCheckBox("fixer comportement")
        self.fixes.append(self.fix_behavior)
        self.fix_line.addWidget(self.fix_behavior)

        self.fix_personality = QCheckBox("fixer personnalité")
        self.fixes.append(self.fix_personality)
        self.fix_line.addWidget(self.fix_personality)

        self.fix_accessories = QCheckBox("fixer accessoire")
        self.fixes.append(self.fix_accessories)
        self.fix_line.addWidget(self.fix_accessories)

        self.layout.addLayout(self.fix_line)

        fix_buttons_lines = QHBoxLayout()
        self.reset_button = QPushButton("Libérer tous les champs")
        self.reset_button.clicked.connect(self.reset_all_fixes)
        fix_buttons_lines.addWidget(self.reset_button)
        self.fix_all_button = QPushButton("Fixer tous les champs")
        self.fix_all_button.clicked.connect(self.set_all_fixes)
        fix_buttons_lines.addWidget(self.fix_all_button)
        self.invert_button = QPushButton("Inverser les champs")
        self.invert_button.clicked.connect(self.invert_all_fixes)
        fix_buttons_lines.addWidget(self.invert_button)

        self.layout.addLayout(fix_buttons_lines)

        self.generate_button = QPushButton("Générer PNJ")
        self.generate_button.setFont(npc_font)
        self.generate_button.setFixedHeight(75)
        self.generate_button.clicked.connect(lambda: self.get_generated())
        self.layout.addWidget(self.generate_button)

        self.copy_npc_button = QPushButton("Copier PNJ")
        self.copy_npc_button.clicked.connect(self.get_description)
        self.layout.addWidget(self.copy_npc_button)

        game_selection = QHBoxLayout()
        game_selection.addWidget(QLabel("Jeu :"), 0, Qt.AlignRight)
        self.game_combo = QComboBox()
        self.game_combo.addItems(["Star Wars", "OGL"])
        self.game_combo.currentTextChanged.connect(self.set_characteristics)
        game_selection.addWidget(self.game_combo)
        self.layout.addLayout(game_selection)

        self.stat_button = QPushButton("Générer caractéristiques")
        self.stat_button.setFont(npc_font)
        self.stat_button.setFixedHeight(75)
        self.stat_button.clicked.connect(self.get_characteristics)
        self.layout.addWidget(self.stat_button)

        self.carac_line = QHBoxLayout()

        stat_font = QFont()
        stat_font.setPointSize(50)
        self.stat_1_group = QGroupBox("Vigueur")
        self.stat_1_group.setFont(npc_font)
        stat_1_layout = QVBoxLayout()
        self.stat_1 = QLineEdit()
        self.stat_1.setFont(stat_font)
        stat_1_layout.addWidget(self.stat_1, 0, Qt.AlignCenter)
        self.stat_1_group.setLayout(stat_1_layout)
        self.carac_line.addWidget(self.stat_1_group)

        self.stat_2_group = QGroupBox("Agilité")
        self.stat_2_group.setFont(npc_font)
        stat_2_layout = QVBoxLayout()
        self.stat_2 = QLineEdit()
        self.stat_2.setFont(stat_font)
        stat_2_layout.addWidget(self.stat_2, 0, Qt.AlignCenter)
        self.stat_2_group.setLayout(stat_2_layout)
        self.carac_line.addWidget(self.stat_2_group)

        self.stat_3_group = QGroupBox("Intelligence")
        self.stat_3_group.setFont(npc_font)
        stat_3_layout = QVBoxLayout()
        self.stat_3 = QLineEdit()
        self.stat_3.setFont(stat_font)
        stat_3_layout.addWidget(self.stat_3, 0, Qt.AlignCenter)
        self.stat_3_group.setLayout(stat_3_layout)
        self.carac_line.addWidget(self.stat_3_group)

        self.stat_4_group = QGroupBox("Ruse")
        self.stat_4_group.setFont(npc_font)
        stat_4_layout = QVBoxLayout()
        self.stat_4 = QLineEdit()
        self.stat_4.setFont(stat_font)
        stat_4_layout.addWidget(self.stat_4, 0, Qt.AlignCenter)
        self.stat_4_group.setLayout(stat_4_layout)
        self.carac_line.addWidget(self.stat_4_group)

        self.stat_5_group = QGroupBox("Volonté")
        self.stat_5_group.setFont(npc_font)
        stat_5_layout = QVBoxLayout()
        self.stat_5 = QLineEdit()
        self.stat_5.setFont(stat_font)
        stat_5_layout.addWidget(self.stat_5, 0, Qt.AlignCenter)
        self.stat_5_group.setLayout(stat_5_layout)
        self.carac_line.addWidget(self.stat_5_group)

        self.stat_6_group = QGroupBox("Présence")
        self.stat_6_group.setFont(npc_font)
        stat_6_layout = QVBoxLayout()
        self.stat_6 = QLineEdit()
        self.stat_6.setFont(stat_font)
        stat_6_layout.addWidget(self.stat_6, 0, Qt.AlignCenter)
        self.stat_6_group.setLayout(stat_6_layout)
        self.carac_line.addWidget(self.stat_6_group)

        self.layout.addLayout(self.carac_line)

        note_group = QGroupBox("Notes")
        note_layout = QVBoxLayout()
        self.additional_note = QTextEdit()
        note_layout.addWidget(self.additional_note)
        note_group.setLayout(note_layout)
        self.layout.addWidget(note_group)

        self.setLayout(self.layout)

    def set_all_fixes(self):
        for box in self.fixes:
            box.setChecked(True)

    def reset_all_fixes(self):
        for box in self.fixes:
            box.setChecked(False)

    def invert_all_fixes(self):
        for box in self.fixes:
            box.setChecked(not box.isChecked())

    def get_generated(self):
        traits = self.npc.generate(*self.tags.text().split(', '))
        self.gender = traits["gender"]
        if self.gender == WOM:
            e_gender = 'e'
        else:
            e_gender = ""
        if FEM in self.npc.tags[traits['accessories'].upper()]:
            det_accessories = "une"
        elif MASC in self.npc.tags[traits['accessories'].upper()]:
            det_accessories = "un"
        elif PLUR in self.npc.tags[traits['accessories'].upper()]:
            det_accessories = "de"
        elif PLURS in self.npc.tags[traits['accessories'].upper()]:
            det_accessories = "des"
        else:
            det_accessories = ""
        if not self.fix_name.isChecked():
            self.name_label.setText(traits['name'])
        if not self.fix_job.isChecked():
            self.job_label.setText(f"un{e_gender} {traits['job']}")
            self.job_label.setToolTip(self.tool_tip["JOBS"].get(
                traits['job'], "Occupation inconnue"))
            self.last_job = traits["job"]
        if not self.fix_specie.isChecked():
            self.specie_label.setText(traits['specie'])
            self.specie_label.setToolTip(self.tool_tip["SPECIES"].get(
                self.specie_label.text(), "Espèce inconnue"))
        if not self.fix_appearance.isChecked():
            self.appearance_label.setText(traits['appearance'])
        if not self.fix_behavior.isChecked():
            self.behavior_label.setText(traits['behavior'])
        if not self.fix_personality.isChecked():
            self.personality_label.setText(traits['personality'])
        if not self.fix_accessories.isChecked():
            self.accessories_label.setText(
                f"{det_accessories} {traits['accessories']}")

    def set_tab_name(self):
        self.parent.tabs.setTabText(self.parent.tabs.currentIndex(),
                                    self.name_label.text())

    def get_description(self):
        npc_description = f"{self.name_label.text()} est {self.job_label.text()} {self.specie_label.text()} " \
                          f"plutôt {self.appearance_label.text()}, {self.behavior_label.text()}, semble être " \
                          f"{self.personality_label.text()} et a {self.accessories_label.text()}"
        QClipboard().setText(npc_description)

    def set_characteristics(self):
        if self.game_combo.currentText() == STAR_WARS:
            self.stat_1_group.setTitle("Vigueur")
            self.stat_2_group.setTitle("Agilité")
            self.stat_3_group.setTitle("Intelligence")
            self.stat_4_group.setTitle("Ruse")
            self.stat_5_group.setTitle("Volonté")
            self.stat_6_group.setTitle("Présence")
        elif self.game_combo.currentText() == OGL:
            self.stat_1_group.setTitle("Force")
            self.stat_2_group.setTitle("Dexterité")
            self.stat_3_group.setTitle("Constitution")
            self.stat_4_group.setTitle("Intelligence")
            self.stat_5_group.setTitle("Sagesse")
            self.stat_6_group.setTitle("Charisme")

    def get_characteristics(self):
        job_key = self.last_job \
            if self.gender == MAN and GENDERED in self.npc.tags[self.last_job.upper()] \
            else apply_gender(self.last_job)
        stat_1, stat_2, stat_3, stat_4, stat_5, stat_6 = \
            self.npc.get_characteristics(
                GAMES[self.game_combo.currentText()],
                self.specie_label.text().upper(),
                job_key
            )
        self.stat_1.setText(f"{stat_1}")
        self.stat_2.setText(f"{stat_2}")
        self.stat_3.setText(f"{stat_3}")
        self.stat_4.setText(f"{stat_4}")
        self.stat_5.setText(f"{stat_5}")
        self.stat_6.setText(f"{stat_6}")

    def tags_selection(self):
        def add_tags():
            added_tags = ""
            for _tag, box in tags.items():
                if box.isChecked():
                    added_tags += _tag + ', '
            self.tags.setText(added_tags.strip(', '))

        selection = QDialog(self.parent)
        layout = QVBoxLayout()
        tags = dict()
        for tag in self.npc.get_tag_list():
            tags[tag] = QCheckBox(tag)
            layout.addWidget(tags[tag])
        button_line = QHBoxLayout()
        add_button = QPushButton("Ajouter")
        add_button.clicked.connect(add_tags)
        add_button.clicked.connect(selection.close)
        button_line.addWidget(add_button)
        close_button = QPushButton("Annuler")
        close_button.clicked.connect(selection.close)
        button_line.addWidget(close_button)
        layout.addLayout(button_line)
        selection.setLayout(layout)
        selection.exec_()
Exemplo n.º 18
0
class Window(QWidget):
    def __init__(self):
        # call the constructor of the parent (QWidget)
        super().__init__()

        # check if it the first time for user to plot
        self.firstTime = False

        # set title  and geometry for the window
        self.setWindowTitle("Function Plotter")
        self.setGeometry(500, 400, 400, 200)

        # give orange background to the window
        palette = self.palette()
        palette.setColor(QPalette.Window, QColor(150, 150, 150))
        self.setPalette(palette)
        self.setAutoFillBackground(True)

        # set minimum width and height for the window
        self.setMinimumHeight(200)
        self.setMinimumWidth(400)
        self.setMaximumHeight(200)
        self.setMaximumWidth(400)

        # set icon for the application at run time and center the application window with the primary screen
        self.setIcon()
        self.center()

        # setup the grid layout design and components
        self.createGridLayout()
        self.vbox = QVBoxLayout()
        self.vbox.addWidget(self.groupBox)
        self.vbox.setAlignment(Qt.AlignCenter | Qt.AlignTop)
        self.setLayout(self.vbox)

    # set icon for the application
    def setIcon(self):
        appIcon = QIcon("icon.png")
        self.setWindowIcon(appIcon)

    # reading the data from text input and apply check tests
    def readData(self):
        # read the equation and check if there is an actual input
        equation = self.equationInput.text()
        if equation == '':
            self.aboutBox("Empty section", "Please enter an equation")
            return
        # remove spaces from the equation and check if the equation has valid variable name
        equation = removeSpaces(equation)
        varName, _ = getVariableName(equation)
        check, error = checkVarName(equation, varName)
        if not check:
            self.aboutBox("Wrong equation", error)
            return

        # check min and max value if it's a real number and the text input isn't empty
        maxValue = self.maxInput.text()
        if maxValue == '':
            self.aboutBox("Empty section", "Please enter maximum value")
            return
        try:
            maxValue = float(maxValue)
        except ValueError:
            self.aboutBox(
                "Wrong range",
                "Invalid value for maximum, please enter float or integer value"
            )
            return
        minValue = self.minInput.text()
        if minValue == '':
            self.aboutBox("Empty section", "Please enter minimum value")
            return
        try:
            minValue = float(minValue)
        except ValueError:
            self.aboutBox(
                "Wrong range",
                "Invalid value for minimum, please enter float or integer value"
            )
            return

        # the max value should be greater than min value
        if minValue >= maxValue:
            self.aboutBox("Wrong range",
                          "Your maximum value should be greater than minimum")
            return

        # process the equation by trying to solve it with max value and check if there is error with operatos, operands or parentheses
        ops = trimTerms(equation, varName)
        temp_ops = replaceVar(ops, varName, str(maxValue))
        testVal, error = functionCalculator(temp_ops)

        if error != None:
            self.aboutBox("Evaluation error", error)
            return

        # function to evaluate f(x) array and return f(x) and x lists to be plotted
        fx, x = self.evaluateFunction(ops, maxValue, minValue, varName)

        # plot the graph
        self.plotGraph(fx, x, varName)

    def plotGraph(self, fx, x, varName):
        # remove the old figure if user request another equation
        if self.firstTime:
            self.fig.clear()
            self.vbox.removeWidget(self.toolbar)
            self.vbox.removeWidget(self.canvas)

        # set first time to be True, to remove the old figures
        self.firstTime = True

        # set the figure and toolbar and add it to the window
        self.fig = Figure(figsize=(7, 5),
                          dpi=65,
                          facecolor=(1, 1, 1),
                          edgecolor=(0, 0, 0))
        self.canvas = FigureCanvas(self.fig)
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.vbox.addWidget(self.toolbar)
        self.vbox.addWidget(self.canvas)

        # set new geometry to the window to fit the graph
        self.resize(400, 500)
        self.setMinimumHeight(500)
        self.setMaximumHeight(500)

        # plot the graph and set the labels
        self.ax = self.fig.add_subplot(111)
        self.ax.plot(x, fx)
        if varName == '':
            varName = 'x'
        self.ax.set_xlabel(varName)
        self.ax.set_ylabel('f(' + varName + ')')

    # QMessageBox which shows any error for the user
    def aboutBox(self, title, error):
        QMessageBox.about(self, title, error)

    def evaluateFunction(self, ops, maxVal, minVal, varName):
        # make array with start = minVal, end, maxVal and step for 0.25 for some accuracy
        x = np.arange(minVal, maxVal, 0.25)
        fx = []
        # loop over each number(i) and evaluate f(i) then add it to f(x) list
        for number in x:
            temp_ops = replaceVar(ops, varName, number)
            val, _ = functionCalculator(temp_ops)
            fx.append(val)

        return fx, x

    # to center the application window at the beginning
    def center(self):
        qRect = self.frameGeometry()
        centerPoint = QtGui.QGuiApplication.primaryScreen().availableGeometry(
        ).center()
        qRect.moveCenter(centerPoint)
        self.move(qRect.topLeft())

    def createGridLayout(self):
        # make group box with headline then add the gridlayout to it
        self.groupBox = QGroupBox("Please fill next sections")
        self.groupBox.setFont(QFont("Helvetica", 12))
        self.groupBox.setMaximumWidth(400)
        self.groupBox.setMaximumHeight(200)
        # create gridlayout with spacing between columns and rows
        gridLayout = QGridLayout()
        gridLayout.setSpacing(10)

        # set equation text input
        self.equationInput = QLineEdit()
        self.equationInput.setMaximumHeight(30)
        #self.equationInput.setMaximumWidth(175)
        self.equationInput.setPlaceholderText("Enter your equation")
        gridLayout.addWidget(self.equationInput, 0, 0, 1, 0)

        # set max value text input
        self.maxInput = QLineEdit()
        self.maxInput.setMaximumHeight(30)
        self.maxInput.setMaximumWidth(175)
        self.maxInput.setPlaceholderText("Enter maximum value")
        gridLayout.addWidget(self.maxInput, 1, 0)

        # set min value text input
        self.minInput = QLineEdit()
        self.minInput.setMaximumHeight(30)
        self.minInput.setMaximumWidth(175)
        self.minInput.setPlaceholderText("Enter minimum value")
        gridLayout.addWidget(self.minInput, 1, 1)

        # set Plot push button with green color and an icon
        plotButton = QPushButton("Plot")
        plotButton.setStyleSheet("background-color: green")
        plotButton.setIcon(QIcon("curve.png"))
        plotButton.setMaximumHeight(30)
        plotButton.setMaximumWidth(75)
        # when button is clicked, call readData and then will plot the function
        plotButton.clicked.connect(self.readData)
        gridLayout.addWidget(plotButton, 2, 0)

        # add gridlayout to the group box
        self.setLayout(gridLayout)
        self.groupBox.setLayout(gridLayout)