def __init__(self, summary_plots=None):
        super(SummaryWindow, self).__init__()

        ## Create GUI Layout
        layout = QVBoxLayout()

        self.fig, self.axs = summary_plots()
        for axis in self.axs:
            axis.tick_params(axis='both', which='major', labelsize=9)
            axis.xaxis.label.set_fontsize(10)
            axis.yaxis.label.set_fontsize(10)
        self.fig.subplots_adjust(bottom=0.11)
        self.fig.subplots_adjust(hspace=0.3)
        self.canvas = FigureCanvas(self.fig)
        self.toolbar = NavigationToolbar(self.canvas, self)
        # Attach figure to the layout
        lf = QVBoxLayout()
        lf.addWidget(self.toolbar)
        lf.addWidget(self.canvas)
        layout.addLayout(lf)

        # add quit button
        bq = QPushButton("QUIT")
        bq.pressed.connect(self.close)
        lb = QVBoxLayout()  # Layout for buttons
        lb.addWidget(bq)
        layout.addLayout(lb)

        self.setLayout(layout)
        self.setGeometry(100, 150, 1500, 900)
        # self.adjustSize()
        self.show()
        self.setWindowTitle('Last experiment summary')
Exemple #2
0
def startGUI():
    app = QApplication([])
    app.setStyle('Fusion')
    if opts.timeclockOpts["darkTheme"]:
        pass
    window = QWidget()
    window.setWindowTitle(opts.timeclockOpts["title"])
    window.setWindowIcon(
        QtGui.QIcon("../data/assets/" + opts.timeclockOpts["logo"]))
    mainLayout = QVBoxLayout()
    mainLayout.setSpacing(20)

    mainLayout.addLayout(makeTitle())

    global tabsObject
    tabsObject = makeNameArea()
    mainLayout.addWidget(tabsObject)
    updateNamesTable()

    mainLayout.addLayout(makeActions(app))

    window.setLayout(mainLayout)
    window.show()
    print("1024  x  768")
    print(window.width(), " x ", window.height())
    print("", 1024 - window.width(), "\t", 768 - window.height())
    app.exec()
Exemple #3
0
    def initUI(self):
        self.setWindowTitle("查看回收站文件夹内容")
        self.form = QVBoxLayout()
        for item in iter(self.files):
            ico = QPushButton(set_file_icon(item.name), item.name)
            ico.setStyleSheet(
                "QPushButton {border:none; background:transparent; color:black;}"
            )
            ico.adjustSize()
            it = QLabel(f"<font color='#CCCCCC'>({item.size})</font>")
            hbox = QHBoxLayout()
            hbox.addWidget(ico)
            hbox.addStretch(1)
            hbox.addWidget(it)
            self.form.addLayout(hbox)

        self.form.setSpacing(10)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setOrientation(Qt.Orientation.Horizontal)
        self.buttonBox.setStandardButtons(
            QDialogButtonBox.StandardButton.Close)
        self.buttonBox.button(
            QDialogButtonBox.StandardButton.Close).setText("关闭")
        self.buttonBox.setStyleSheet(btn_style)
        self.buttonBox.rejected.connect(self.reject)

        vbox = QVBoxLayout()
        vbox.addLayout(self.form)
        vbox.addStretch(1)
        vbox.addWidget(self.buttonBox)
        self.setLayout(vbox)
Exemple #4
0
    def initUI(self):

        OVER_CAPACITY = 750

        sld = QSlider(Qt.Orientations.Horizontal, self)
        sld.setFocusPolicy(Qt.FocusPolicy.NoFocus)
        sld.setRange(1, OVER_CAPACITY)
        sld.setValue(75)
        sld.setGeometry(30, 40, 150, 30)

        self.c = Communicate()
        self.wid = BurningWidget()
        self.c.updateBW[int].connect(self.wid.setValue)

        sld.valueChanged[int].connect(self.changeValue)
        hbox = QHBoxLayout()
        hbox.addWidget(self.wid)
        vbox = QVBoxLayout()
        vbox.addStretch(1)
        vbox.addLayout(hbox)
        self.setLayout(vbox)

        self.setGeometry(300, 300, 390, 210)
        self.setWindowTitle('Burning widget')
        self.show()
class AddDialog(QDialog):
    """Add Contact dialog."""

    def __init__(self, parent=None):
        """Initializer"""
        super().__init__(parent=parent)
        self.setWindowTitle("Add Contact")
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)
        self.data = None

        self.setupUI()

    def setupUI(self):
        """Setup the Add Contact dialog's GUI."""
        # Create line edits for data fields
        self.nameField = QLineEdit()
        self.nameField.setObjectName("Name")
        self.jobField = QLineEdit()
        self.jobField.setObjectName("Job")
        self.emailField = QLineEdit()
        self.emailField.setObjectName("Email")
        # Lay out the data fields
        layout = QFormLayout()
        layout.addrow("Name:", self.nameField)
        layout.addrow("Job:", self.jobField)
        layout.addrow("Email:", self.emailField)
        self.layout.addLayout(layout)
        # add standard buttons to the dialog and conntect them
        self.buttonsBox = QDialogButtonBox(self)
        self.buttonsBox.setOrientation(Qt.Horizontal)
        self.buttonsBox.setStandardButtons(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel
        )
        self.buttonsBox.accepted.connect(self.accept)
        self.buttonsBox.rejected.connect(self.reject)
        self.layout.addWidget(self.buttonsBox)

    def accept(self):
        """Accept the data provided through the dialog."""
        self.data = []
        for field in (self.nameField, self.jobField, self.emailField):
            if not field.text():
                QMessageBox.critical(
                    self,
                    "Error!",
                    f"You must provide a contact's{field.objectName()}",
                )
                self.data = None  # reset .data
                return

            self.data.append(field.text())

        if not self.data:
            return()

        super().accept()
    def __init__(
        self,
        parent=None,
        buttons=None,
        exercises=None,
        index: int = None,
    ):
        super(ChangeKeyDialog, self).__init__(parent)
        layout = QVBoxLayout(self)
        self.setLayout(layout)
        widget = QWidget()
        keyLayout = QVBoxLayout()
        widget.setStyleSheet("""
        QWidget{
            border-radius: 12px;
            border: 1px solid grey;
            background-color: #b5b5b5;
            color: white;
            font-size: 40px;
        }
        """)
        # widget.setFixedSize(100, 100)
        self.currentKeyLabel = QLabel('W')
        keyLayout.addWidget(self.currentKeyLabel)
        keyLayout.setAlignment(self.currentKeyLabel, Qt.Alignment.AlignCenter)
        widget.setLayout(keyLayout)

        label = QLabel("Press a key to swap")
        emptyKey = QPushButton('Use empty slot')
        emptyKey.setFocusPolicy(Qt.FocusPolicy.ClickFocus)
        emptyKey.clicked.connect(self.useEmpty)

        acceptKey = QPushButton('Accept')
        acceptKey.clicked.connect(self.accept)
        acceptKey.setFocusPolicy(Qt.FocusPolicy.ClickFocus)

        layout.addWidget(label)
        layout.addWidget(widget)
        actions = QHBoxLayout()
        actions.addWidget(emptyKey)
        actions.addWidget(acceptKey)
        layout.addLayout(actions)
        layout.setAlignment(widget, Qt.Alignment.AlignCenter)
        self.buttons = buttons
        self.exercises = exercises
        self.index = index

        self.monitor = KeyMonitor()
        self.monitor.start_monitoring()
        self.currentKey = self.monitor.currentKey

        self.timer = QTimer()
        self.timer.timeout.connect(self.onTimeout)
        self.timer.start()
        print("Dialog init done!")
    def __init__(self):
        super(MainWidget, self).__init__()
        self.resize(500, 600)
        self.setWindowTitle("喜马拉雅下载 by[Zero] " + __VERSION__)
        self.mainlayout = QVBoxLayout()
        self.setLayout(self.mainlayout)
        self.groupbox = QGroupBox("选择类型")
        self.groupbox.setFixedHeight(50)
        hlayout = QHBoxLayout(self.groupbox)
        self.signal_m4a = QRadioButton("单个下载")
        self.mut_m4a = QRadioButton("专辑下载")
        self.vip_signal_m4a = QRadioButton("VIP单个下载")
        self.vip_m4a = QRadioButton("VIP专辑下载")

        hlayout.addWidget(self.signal_m4a)
        hlayout.addWidget(self.mut_m4a)
        hlayout.addWidget(self.vip_signal_m4a)
        hlayout.addWidget(self.vip_m4a)
        self.mainlayout.addWidget(self.groupbox)

        frame01 = QFrame(self)
        child_layout = QVBoxLayout()
        print(self.width())
        label01 = QLabel("链   接", self)
        label02 = QLabel("下载目录", self)
        self.url_lineedit = QLineEdit(self)
        self.dir_lineedit = QLineEdit(self)
        hlayout01 = QHBoxLayout()
        hlayout01.addWidget(label01, 1)
        hlayout01.addWidget(self.url_lineedit, 9)
        hlayout02 = QHBoxLayout()
        hlayout02.addWidget(label02, 1)
        hlayout02.addWidget(self.dir_lineedit, 9)
        child_layout.addLayout(hlayout01)
        child_layout.addLayout(hlayout02)
        child_layout.setContentsMargins(
            5, 0, 5, 0)  #(int left, int top, int right, int bottom)
        frame01.setLayout(child_layout)
        self.download_progressbar = QProgressBar()
        self.download_progressbar.setAlignment(
            QtCore.Qt.Alignment.AlignCenter)  #文字居中
        self.download_progressbar.setValue(88)
        self.download_btn = QPushButton("开始下载")
        self.show_plaintextedit = QPlainTextEdit()
        self.show_plaintextedit.setMinimumHeight(400)
        self.mainlayout.addWidget(frame01)
        self.mainlayout.addWidget(self.download_progressbar)
        self.mainlayout.addWidget(self.download_btn)
        self.mainlayout.addWidget(self.show_plaintextedit)
        self.mainlayout.addStretch()
        ### 设置stylesheet
        self.download_btn.setStyleSheet(
            'QPushButton:pressed{ text-align: center;background-color:red;}')
Exemple #8
0
 def show_setting(self, conf: dict, layout: QGridLayout):
     groups = list()
     x = 0
     y = 0
     shape = 3
     for key in conf.keys():
         if type(conf[key]) == bool or type(conf[key]) == str:
             continue
         conf_title = conf[key]["title"]
         conf_enabled = conf[key]["enabled"]
         conf_times = conf[key]["times"]
         group = QGroupBox(conf_title)
         group.setStyleSheet("QGroupBox{border-radius:5px;}")
         group.setToolTip(conf_title + "  的设置")
         enabled = QCheckBox("启用")
         enabled.setObjectName(key)
         enabled.setToolTip("单击切换开关状态")
         enabled.setChecked(conf_enabled)
         enabled.setStyleSheet(
             "QCheckBox::indicator{width:10px;height:10px;border:none;border-radius:5px;background:#9BE3DE;}QCheckBox::indicator:unchecked{background:#BEEBE9;}QCheckBox::indicator:unchecked:hover{background:#9AD3BC;}QCheckBox::indicator:checked{background:#95E1D3;}QCheckBox::indicator:checked:hover{background:#98DED9;}"
         )
         times = QHBoxLayout()
         times_label = QLabel("次数:")
         times_label.setStyleSheet(
             "QLabel{background:transparent;border:none;border-radius:5px;}"
         )
         times_input = EnhancedEdit()
         times_input.setObjectName(key)
         times_input.setText(str(conf_times))
         times_input.setToolTip("仅限正整数")
         times_input.setValidator(
             QRegularExpressionValidator(
                 QRegularExpression("^[1-9][0-9]{1,8}$")))
         times_input.setStyleSheet(
             "QLineEdit{border:1px solid #F3EAC2;border-radius:5px;background:transparent;}QLineEdit:hover{border:1px solid #F5B461;}"
         )
         times.addWidget(times_label)
         times.addWidget(times_input)
         group_layout = QVBoxLayout()
         group_layout.addWidget(enabled)
         group_layout.addLayout(times)
         group.setLayout(group_layout)
         group.setObjectName(key)
         groups.append(group)
     for group in groups:
         if y >= shape:
             x = x + 1
             y = 0
         layout.addWidget(group, x, y)
         y = y + 1
     self.logger.debug("最后的元素位置:(%d,%d)" % (x, y))
     return (x, y)
Exemple #9
0
class Settings(QDialog):
    """Open new window with editable options that effect gameplay."""
    def __init__(self, parent=None, window=None):
        """Construct Settings Dialog.

        Args:
            parent (QWidget, optional) Parent widget object. Defaults to None.
            window (QWidget, optional) Program's MainWindow. Defaults to None.
        """
        super().__init__(parent=parent)
        self.setObjectName("Preferences")
        self.window = window
        self.setSizeGripEnabled(False)
        self.setObjectName("Settings")
        self.setWindowTitle("Preferences")
        self.setModal(True)
        self.vlayout = QVBoxLayout()
        self.setLayout(self.vlayout)
        self.playersLabel = QLabel("Number of Players", parent=self)
        self.decksLabel = QLabel("Number of Decks", parent=self)
        self.playersSpin = QSpinBox(parent=self)
        self.decksSpin = QSpinBox(parent=self)
        self.hLayout1 = QHBoxLayout()
        self.hLayout2 = QHBoxLayout()
        self.hLayout1.addWidget(self.playersLabel)
        self.hLayout1.addWidget(self.playersSpin)
        self.hLayout2.addWidget(self.decksLabel)
        self.hLayout2.addWidget(self.decksSpin)
        self.vlayout.addLayout(self.hLayout1)
        self.vlayout.addLayout(self.hLayout2)
        self.hLayout3 = QHBoxLayout()
        self.okayButton = QPushButton("Submit", parent=self)
        self.cancelButton = QPushButton("Cancel", parent=self)
        self.hLayout3.addWidget(self.okayButton)
        self.hLayout3.addWidget(self.cancelButton)
        self.vlayout.addLayout(self.hLayout3)
        self.okayButton.pressed.connect(self.accept)
        self.cancelButton.pressed.connect(self.reject)
        self.finished.connect(self.finishedSignal)

    def accept(self):
        """Close Window."""
        return self.window.driver.reset_prefs(self.decksSpin.value(),
                                              self.playersSpin.value())

    def finishedSignal(self):
        """When Settings Window returns accept or reject signals."""
        self.window.dealer.deck_count = self.decksSpin.value()
        self.window.dealer.player_count = self.playersSpin.value()
Exemple #10
0
    def __init__(self):
        global serialPort, baud, fmt
        self.serialLogState = False
        self.fmts = ['bin', 'oct', 'dec', 'hex', 'csv', 'csv+', 'ascii']
        self.baudList = [
            4800, 7200, 9600, 14400, 19200, 28800, 38400, 57600, 76800, 115200,
            230400, 460800, 921600, 1000000, 2000000, 4000000
        ]
        fmt = self.fmts.index(fmt)
        super().__init__()
        layoutA = QHBoxLayout()

        self.baudBox = QComboBox()
        self.getBaud()
        layoutA.addWidget(self.baudBox)

        self.formatBox = QComboBox()
        self.getFormat()
        layoutA.addWidget(self.formatBox)

        layoutB = QHBoxLayout()
        self.portBox = QComboBox()
        self.getPorts()
        layoutB.addWidget(self.portBox)

        parentLayout = QVBoxLayout()
        parentLayout.addLayout(layoutB)
        parentLayout.addLayout(layoutA)

        self.setLayout(parentLayout)

        self.portBox.currentTextChanged.connect(self.portSelected)
        self.portBox.setCurrentIndex(len(self.ports) - 1)

        self.baudBox.currentTextChanged.connect(self.baudSelected)
        try:
            self.baudBox.setCurrentIndex(self.baudList.index(baud))
        except:
            self.baudBox.setCurrentIndex(-1)

        self.formatBox.currentTextChanged.connect(self.formatSelected)
        self.formatBox.setCurrentIndex(fmt)

        self.button1 = QPushButton()
        self.button1.setText("start")
        self.button1.released.connect(self.btn1Clicked)
        layoutA.addWidget(self.button1)
Exemple #11
0
 def __init__(self):
     super(MainUi, self).__init__()
     self.setFixedSize(600,500)
     self.setWindowTitle("妹子图爬虫工具  version: 1.0.0 ")
     self.download_progressbar = QProgressBar()
     self.download_progressbar.setAlignment(QtCore.Qt.Alignment.AlignCenter)#文字居中
     self.download_progressbar.setStyleSheet(".QProgressBar::chunk { background-color: red;}")#背景
     self.download_progressbar.setValue(100)
     label01 = QLabel("下载URL:")
     label02 = QLabel("下载目录:")
     self.url_input    = QLineEdit()
     self.url_input.setText("https://www.mzitu.com/221746")
     self.url_input.setContentsMargins(0,0,0,0)
     self.download_dir = QLineEdit()
     self.download_dir.setContentsMargins(0,0,0,0)
     self.start_btn    = QPushButton("开始爬虫")
     self.start_btn.setFixedHeight(50)
     self.start_btn.setContentsMargins(0,0,0,0)
     inputlayout = QGridLayout()
     inputlayout.addWidget(label01, 0, 0) #第0行 0列
     inputlayout.addWidget(label02, 1, 0)
     inputlayout.addWidget(self.url_input, 0, 1)
     inputlayout.addWidget(self.download_dir, 1, 1)
     inputlayout.addWidget(self.start_btn, 0, 2, 2,1,QtCore.Qt.Alignment.AlignRight) #起始行,起始列, 占行数,占列数
     inputlayout.setColumnStretch(0, 1)  #设置每一列比例
     inputlayout.setColumnStretch(1, 10)
     inputlayout.setColumnStretch(2, 1)
     vlayout = QVBoxLayout()
     vlayout.addLayout(inputlayout)
     vlayout.addWidget(self.download_progressbar)
     self.frame = QFrame()
     self.frame.setFixedHeight(400)
     vlayout.addWidget(self.frame)
     vlayout.addStretch()
     inputlayout.setContentsMargins(0,0,0,0)
     vlayout01 = QVBoxLayout()
     self.frame.setLayout(vlayout01)
     self.qtablewidget = QTableWidget(1,3)
     self.qtablewidget.setHorizontalHeaderLabels(['目录','下载图片总数目', '删除'])
     vlayout01.addWidget(self.qtablewidget)
     self.qtablewidget.setColumnWidth(0, 358)  # 将第0列的单元格,设置成300宽度
     self.qtablewidget.setColumnWidth(1, 100 )  # 将第0列的单元格,设置成50宽度
     self.qtablewidget.verticalHeader().setVisible(False) #隐藏水平表头
     #self.qtablewidget.setDisabled(True) #设置不可编辑
     self.setLayout(vlayout)
     self.current_index = 0
Exemple #12
0
    def initUI(self):
        self.setWindowTitle("合并文件")
        self.setWindowIcon(QIcon(SRC_DIR + "upload.ico"))
        self.logo = QLabel()
        self.logo.setPixmap(QPixmap(SRC_DIR + "logo3.gif"))
        self.logo.setStyleSheet("background-color:rgb(0,153,255);")
        self.logo.setAlignment(Qt.AlignmentFlag.AlignCenter)

        # lable
        self.choose_lb = QLabel("选择文件夹")
        # folder
        self.choose_folder = MyLineEdit(self)
        self.choose_folder.setObjectName("choose_folder")
        self.choose_folder.clicked.connect(self.slot_choose_folder)
        self.status = QLabel(self)

        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setOrientation(Qt.Orientation.Horizontal)
        self.buttonBox.setStandardButtons(
            QDialogButtonBox.StandardButton.Ok
            | QDialogButtonBox.StandardButton.Cancel)
        self.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setText("提取")
        self.buttonBox.button(
            QDialogButtonBox.StandardButton.Cancel).setText("关闭")
        self.buttonBox.setStyleSheet(btn_style)

        vbox = QVBoxLayout()
        hbox_head = QHBoxLayout()
        hbox_button = QHBoxLayout()
        hbox_head.addWidget(self.choose_lb)
        hbox_head.addWidget(self.choose_folder)
        hbox_button.addWidget(self.buttonBox)
        vbox.addWidget(self.logo)
        vbox.addStretch(1)
        vbox.addWidget(self.status)
        vbox.addLayout(hbox_head)
        vbox.addStretch(1)
        vbox.addLayout(hbox_button)
        self.setLayout(vbox)
        self.setMinimumWidth(350)

        # 设置信号
        self.buttonBox.accepted.connect(self.slot_btn_ok)
        self.buttonBox.rejected.connect(self.slot_btn_no)
        self.buttonBox.rejected.connect(self.reject)
    def __init__(
        self,
        onValueChanged: Callable[[int], None],
        parent: Optional[QWidget] = None,
        *args: Tuple[Any, Any],
        **kwargs: Tuple[Any, Any],
    ) -> None:
        """
        Slow/fast slider for maze solver agents speed
        """
        super(MazeSolverSpeedControlView, self).__init__(parent=parent,
                                                         *args,
                                                         **kwargs)
        self.setContentsMargins(0, 0, 0, 0)

        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)

        slider = QSlider(Qt.Orientations.Horizontal)
        # minimum of 1 op/s (0 would result in a divide by zero op and thus crash)
        slider.setMinimum(1)
        # maximum of 50 op/s
        slider.setMaximum(70)
        # initial value in the middle
        slider.setValue(35)

        # connect the onValueChange event to the method passed to this widget
        slider.valueChanged.connect(onValueChanged)  # type: ignore

        # slow/fast horizontal labels view
        slowFastLabelsLayout = QHBoxLayout()
        slowFastLabelsLayout.setContentsMargins(0, 0, 0, 0)

        slowLabel = QLabel("Slow")
        fastLabel = QLabel("Fast")

        slowFastLabelsLayout.addWidget(slowLabel)
        slowFastLabelsLayout.addStretch()
        slowFastLabelsLayout.addWidget(fastLabel)

        layout.addWidget(slider)
        layout.addLayout(slowFastLabelsLayout)

        self.setLayout(layout)
Exemple #14
0
    def init_ui(self):
        layout = QVBoxLayout()
        self.setLayout(layout)

        self.text = QTextEdit()
        layout.addWidget(self.text)

        layout2 = QHBoxLayout()
        layout.addLayout(layout2)

        self.combo = QComboBox()
        self.combo.addItem('不自动加换行符')
        self.combo.addItem('结尾自动加\\r\\n')
        self.combo.addItem('结尾自动加\\r')
        self.combo.addItem('结尾自动加\\n')
        self.send_btn = QPushButton('发送')

        layout2.addWidget(self.combo)
        layout2.addWidget(self.send_btn)
Exemple #15
0
    def initUI(self):

        okButton = QPushButton("OK")
        cancelButton = QPushButton("Cancel")

        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(okButton)
        hbox.addWidget(cancelButton)

        vbox = QVBoxLayout()
        vbox.addStretch(1)
        vbox.addLayout(hbox)

        self.setLayout(vbox)

        self.setGeometry(300, 300, 350, 250)
        self.setWindowTitle('Buttons')
        self.show()
class Load_Dialog(QDialog):
    def __init__(self, parent):
        super().__init__(parent)
        self.setWindowTitle('Cargar Fichero')
        self.dlg_v_layout = QVBoxLayout()
        form_layout = QFormLayout()
        self.load_file = QLineEdit()
        self.error_label = QLabel()
        form_layout.addRow('Ruta del archivo:', self.load_file)
        self.dlg_v_layout.addLayout(form_layout)
        self.dlg_v_layout.addWidget(self.error_label)
        buttons_h_layout = QHBoxLayout()
        button_cancel = QPushButton('Cancelar')
        self.button_ok = QPushButton('Aceptar')
        buttons_h_layout.addWidget(button_cancel)
        buttons_h_layout.addWidget(self.button_ok)
        self.dlg_v_layout.addLayout(buttons_h_layout)
        self.setLayout(self.dlg_v_layout)
        button_cancel.clicked.connect(self._clear)
        button_cancel.clicked.connect(self.close)
        self.button_ok.clicked.connect(self._load)

    def _load_file_dialog(self):
        dlg = Load_Dialog(self._view)
        dlg.exec()
        self.file = dlg.file_path_dialog
        try:
            if len(self.file) > 0:
                self.text_load_file = self._Model.load_file(self.file)
                self._view.set_display_text(
                    self.file, self.text_load_file[0], self.text_load_file[1],
                    self.text_load_file[2], self.text_load_file[3],
                    self.text_load_file[4], self.text_load_file[5],
                    self.text_load_file[6], self.text_load_file[7],
                    self.text_load_file[8])
            pass
        except:
            print("Error de carga de ficheros.")

    def _clear(self):
        self.load_file.clear()
        self.file_path_dialog = self.load_file.text()
Exemple #17
0
    def __init__(
        self,
        parent: Optional[QWidget] = None,
        *args: Tuple[Any, Any],
        **kwargs: Tuple[Any, Any],
    ) -> None:
        """
        The 'Log' window view. Shows the current state of the solver at top, and for each history item:
            Left: Human description of command
            Right: Result success or not
        """
        # initialize the solver state history list to a new list
        super(AgentLogView, self).__init__(parent=parent, *args, **kwargs)

        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)

        verticalGroupLayout = QVBoxLayout()
        # self.__currentStateBox = CurrentStateBox("Not set…")
        # verticalGroupLayout.addWidget(self.__currentStateBox)

        # define the vertical scroll area of the log
        logLayoutScrollArea = QScrollArea()
        # enable smart vertical scroll
        logLayoutScrollArea.setVerticalScrollBarPolicy(
            Qt.ScrollBarPolicy.ScrollBarAsNeeded)
        # disable horizontal scroll
        logLayoutScrollArea.setHorizontalScrollBarPolicy(
            Qt.ScrollBarPolicy.ScrollBarAlwaysOff)

        # define our log layout (name on left, result on right) and add to layout
        self.__verticalLogLayout = VerticalLogLayout()
        logLayoutScrollArea.setWidget(self.__verticalLogLayout)

        # add the log layout to the vertical layout
        verticalGroupLayout.addWidget(logLayoutScrollArea)

        layout.addLayout(verticalGroupLayout)

        self.setLayout(layout)
        self.setWindowTitle("Agent Log")
Exemple #18
0
    def displayFilesDock(self):
        """Dock widget that displays the movie file location in a QLineEdit 
        widget, provides a button for opening directories with images and GIFs, 
        and shows the media from the selected folder in a QTreeWidget."""
        self.files_dock = QDockWidget()
        self.files_dock.setWindowTitle("Media Folder")
        self.files_dock.setAllowedAreas(Qt.DockWidgetArea.LeftDockWidgetArea)

        folder_label = QLabel("Media Location:")
        # The QLineEdit widget is set to read-only as a quick way to display
        # the folder path
        self.folder_line = QLineEdit()
        self.folder_line.setMinimumWidth(100)
        self.folder_line.setReadOnly(True)

        open_button = QPushButton("Open...")
        open_button.clicked.connect(self.openDirectory)

        folder_h_box = QHBoxLayout()
        folder_h_box.addWidget(folder_label)
        folder_h_box.addWidget(self.folder_line)
        folder_h_box.addWidget(open_button)

        self.files_tree = QTreeWidget()
        self.files_tree.setHeaderLabel("Media Files")
        self.files_tree.setColumnCount(1)

        # Set up the dock's layout
        dock_v_box = QVBoxLayout()
        dock_v_box.addLayout(folder_h_box)
        dock_v_box.addWidget(self.files_tree)

        dock_container = QWidget()
        dock_container.setLayout(dock_v_box)

        self.files_dock.setWidget(dock_container)
        self.addDockWidget(Qt.DockWidgetArea.LeftDockWidgetArea,
                           self.files_dock)
Exemple #19
0
class StatsFrame(QWidget):
    """Calculate statistics for each turn of the players."""

    label_ssheet = """QLabel {
                    font-size: 15pt;
                    font-weight: bold;
                    padding-right: 5px;
                    color: #fca018;}"""

    def __init__(self, parent=None, window=None):
        super().__init__(parent=parent)
        self.window = window
        self.hlayout = QHBoxLayout()
        self.setLayout(self.hlayout)
        self.vbox1 = QVBoxLayout()
        self.vbox2 = QVBoxLayout()
        self.cardCount = HLabels("Cards in Deck: ", "0")
        self.deckCount = HLabels("Number of Decks: ", "0")
        self.playerCount = HLabels("Number of Players: ", "0")
        self.breaking21 = HLabels("Breaking 21: ", " 0")
        self.exactly = HLabels("Exactly 21: ", " 0")
        self.under21 = HLabels("Under 21: ", " 0")
        self.probabilities = QLabel("Probabilities", parent=self)
        self.quantities = QLabel("Quantities", parent=self)
        self.vbox2.addWidget(self.quantities)
        self.vbox2.addLayout(self.cardCount)
        self.vbox2.addLayout(self.deckCount)
        self.vbox2.addLayout(self.playerCount)
        self.vbox1.addWidget(self.probabilities)
        self.vbox1.addLayout(self.breaking21)
        self.vbox1.addLayout(self.exactly)
        self.vbox1.addLayout(self.under21)
        self.hlayout.addLayout(self.vbox1)
        self.hlayout.addLayout(self.vbox2)
        self.quantities.setStyleSheet(self.label_ssheet)
        self.probabilities.setStyleSheet(self.label_ssheet)
        self.probabilities.setAlignment(Qt.AlignmentFlag(4))
        self.quantities.setAlignment(Qt.AlignmentFlag(4))
        self.labels = {
            "cards": self.cardCount,
            "decks": self.deckCount,
            "players": self.playerCount,
            "breaking": self.breaking21,
            "exactly": self.exactly,
            "under": self.under21,
        }
        self.window.driver.hook(self.labels)
Exemple #20
0
class PyCalcUi(QMainWindow):
    """PyCalc's View (GUI)."""

    def __init__(self):
        """View initializer."""
        super().__init__()
        # Set some main window's properties
        self.setWindowTitle("PyCalc")
        self.setFixedSize(235, 235)
        # Set the central widget and the general layout
        self.generalLayout = QVBoxLayout()
        self._centralWidget = QWidget(self)
        self.setCentralWidget(self._centralWidget)
        self._centralWidget.setLayout(self.generalLayout)
        # Create the display and the buttons
        self._createDisplay()
        self._createButtons()

    def _createDisplay(self):
        """Create the display."""
        # Create the display widget
        self.display = QLineEdit()
        # Set some display's properties
        self.display.setFixedHeight(35)
        self.display.setAlignment(Qt.AlignmentFlag.AlignRight)
        self.display.setReadOnly(True)
        # Add the display to the general layout
        self.generalLayout.addWidget(self.display)

    def _createButtons(self):
        """Create the buttons."""
        self.buttons = {}
        buttonsLayout = QGridLayout()
        # Button text | position on the QGridLayout
        buttons = {
            "7": (0, 0),
            "8": (0, 1),
            "9": (0, 2),
            "/": (0, 3),
            "C": (0, 4),
            "4": (1, 0),
            "5": (1, 1),
            "6": (1, 2),
            "*": (1, 3),
            "(": (1, 4),
            "1": (2, 0),
            "2": (2, 1),
            "3": (2, 2),
            "-": (2, 3),
            ")": (2, 4),
            "0": (3, 0),
            "00": (3, 1),
            ".": (3, 2),
            "+": (3, 3),
            "=": (3, 4),
        }
        # Create the buttons and add them to the grid layout
        for btnText, pos in buttons.items():
            self.buttons[btnText] = QPushButton(btnText)
            self.buttons[btnText].setFixedSize(40, 40)
            buttonsLayout.addWidget(self.buttons[btnText], pos[0], pos[1])
        # Add buttonsLayout to the general layout
        self.generalLayout.addLayout(buttonsLayout)

    def setDisplayText(self, text):
        """Set display's text."""
        self.display.setText(text)
        self.display.setFocus()

    def displayText(self):
        """Get display's text."""
        return self.display.text()

    def clearDisplay(self):
        """Clear the display."""
        self.setDisplayText("")
Exemple #21
0
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.width = 500
        self.height = 500
        self.xPos = 600
        self.yPos = 400
        self.initUI()

    def initUI(self):
        self.setGeometry(self.xPos, self.yPos, self.width, self.height)
        self.vBoxLayout = QVBoxLayout()

        self.slider = Slider(
            direction=Qt.Orientation.Horizontal,
            duration=750,
            animationType=QEasingCurve.Type.OutQuad,
            wrap=False,
        )

        self.label1 = QLabel()
        self.label1.setText('First Slide')
        self.label1.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.label1.setStyleSheet(
            'QLabel{background-color: rgb(245, 177, 66); color: rgb(21, 21, 21); font: 25pt;}'
        )
        self.slider.addWidget(self.label1)

        self.label2 = QLabel()
        self.label2.setText('Second Slide')
        self.label2.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.label2.setStyleSheet(
            'QLabel{background-color: rgb(21, 21, 21); color: rgb(245, 177, 66); font: 25pt;}'
        )
        self.slider.addWidget(self.label2)

        self.label3 = QLabel()
        self.label3.setText('Third Slide')
        self.label3.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.label3.setStyleSheet(
            'QLabel{background-color: rgb(93, 132, 48); color: rgb(245, 177, 66); font: 25pt;}'
        )
        self.slider.addWidget(self.label3)

        self.buttonPrevious = QPushButton()
        self.buttonPrevious.setText('Previous Slide')
        self.buttonPrevious.clicked.connect(self.slider.slidePrevious)

        self.buttonNext = QPushButton()
        self.buttonNext.setText('Next Slide')
        self.buttonNext.clicked.connect(self.slider.slideNext)

        self.buttonLayout = QHBoxLayout()
        self.buttonLayout.addWidget(self.buttonPrevious)
        self.buttonLayout.addWidget(self.buttonNext)

        self.vBoxLayout.addWidget(self.slider)
        self.vBoxLayout.addLayout(self.buttonLayout)

        self.centralWidget = QWidget(self)
        self.centralWidget.setLayout(self.vBoxLayout)
        self.setCentralWidget(self.centralWidget)

        self.show()
Exemple #22
0
class PlayerBox(QGroupBox):
    """PlayerBox Subclass of QGroupBox.

    Returns GroupBoxWidget data and cards for each player.
    """

    offsheet = """QGroupBox {
        font-size: 14pt;
        padding: 4px;
        margin: 5px;
        color: #efeefe;
        border: 9px solid #dfa;}"""

    onsheet = """QGroupBox {
        color: red;
        padding: 4px;
        margin: 5px;
        border: 5px solid red;
        border-radius: 2px;}"""

    labelsheet = """QLabel {
        color: #efeefe;
        margin-bottom: 8px;
        font-weight: bold;
        font-size: 14pt;
        font-style: italic;}"""

    scoresheet = """QLabel {
        border: 1px solid #efeefe;
        padding: 3px;
        margin-bottom: 8px;
        color: #efeefe;
        font-weight: bold;
        font-size: 16pt;
        font-style: italic;}"""

    def __init__(self, title, parent=None, player=None):
        """Construct a PlayerBox Widget.

        Args:
            parent (QWidget, optional) Parent widget object. Defaults to None.
            player (Player) The player this box will be assigned to.
        """
        super().__init__(title, parent=parent)
        self.player = player
        self._turn = False
        self.player.set_box(self)
        self.setStyleSheet(self.offsheet)
        self._setupUi()

    def _setupUi(self):
        """Create UI elements."""
        self.vbox = QVBoxLayout()
        self.vbox.setObjectName(self.player.title + "BoxVertLayout")
        self.grid = QGridLayout()
        self.grid.setObjectName(self.player.title + "BoxCardPicsLayout")
        self.hbox = QHBoxLayout()
        self.hbox.setObjectName(self.player.title + "BoxHorizLayout")
        self.vbox.addLayout(self.hbox)
        self.vbox.addLayout(self.grid)
        self.setLayout(self.vbox)
        self._setupLabels()
        self._setupCards()

    def _setupLabels(self):
        """Set up window labels."""
        expolicy = QSizePolicy.Policy.MinimumExpanding
        minpolicy = QSizePolicy.Policy.Minimum
        self.label = QLabel("Score: ")
        self.label.setObjectName("ScoreLabel")
        self.label.setStyleSheet(self.labelsheet)
        self.hbox.addWidget(self.label)
        self.hbox.addSpacerItem(QSpacerItem(10, 0, minpolicy, minpolicy))
        self.scorelabel = QLabel("0")
        self.scorelabel.setObjectName("ScoreValue")
        self.scorelabel.setStyleSheet(self.scoresheet)
        self.hbox.addWidget(self.scorelabel)
        self.hbox.addSpacerItem(QSpacerItem(50, 0, expolicy, minpolicy))

    def _setupCards(self):
        """Create card covers."""
        card = CardWidget(parent=self)
        card.setObjectName("Card1")
        self.addCard(card)
        self.grid.addWidget(card, 0, 0, -1, -1)
        card2 = CardWidget(parent=self)
        card2.setObjectName(self.player.title + "Card2")
        self.addCard(card2)
        self.grid.addWidget(card2, 0, 1, -1, -1)

    @property
    def cardCount(self):
        """Count cards in players hand.

        Returns:
            int: Total number of cards in players hand.
        """
        return len(self.player.cards)

    @property
    def cards(self):
        """Shortcut method accessing players cards property.

        Returns:
            list: List of card widgets.
        """
        return self.player.cards

    def addCard(self, card):
        """Shortcut for adding card widget to players list of cards.

        Args:
            card (obj): CardWidget object.
        """
        self.player.cards.append(card)

    def deleteCard(self, card):
        """Remove card from Players list of cards property."""
        if card in self.player.cards:
            self.player.cards.remove(card)

    def reset(self):
        """Clear PlayerBox of all widgets.

        Called when current round ends and new deal begins.
        """
        while len(self.cards) > 0:
            card = self.cards[0]
            self.grid.removeWidget(card)
            card.setVisible(False)
            card.hide()
            card.destroy(True, True)
            self.deleteCard(card)
            del card
            self.repaint()
            self.update()

    def addWidget(self, card):
        """Add another card to Window.

        Args:
            card (obj): Card object from deck.

        Returns:
            bool: True if successful else None
        """
        if self.cardCount <= 2:
            for widget in self.cards:
                if not widget.has_card():
                    return widget.setCard(card)
        widget = CardWidget(card=card)
        widget.setObjectName("Card" + str(self.cardCount))
        self.grid.addWidget(widget, 0, self.cardCount, -1, -1)
        return self.addCard(widget)

    def isTurn(self):
        """Return True if currently players turn.

        Returns:
            bool: True if it's players turn else false.
        """
        return self._turn

    def turn(self):
        """Flip `self.turn` property False or True.

        Changes the style of PlayerBox to indicate if it
        is or isn't currently players turn.
        """
        if self.isTurn():
            self._turn = False
            self.setStyleSheet(self.offsheet)
        else:
            self._turn = True
            self.setStyleSheet(self.onsheet)
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        # region Create CartPole instance and load initial settings

        # Create CartPole instance
        self.initial_state = create_cartpole_state()
        self.CartPoleInstance = CartPole(initial_state=self.initial_state)

        # Set timescales
        self.CartPoleInstance.dt_simulation = dt_simulation
        self.CartPoleInstance.dt_controller = controller_update_interval
        self.CartPoleInstance.dt_save = save_interval

        # set other settings
        self.CartPoleInstance.set_controller(controller_init)
        self.CartPoleInstance.stop_at_90 = stop_at_90_init
        self.set_random_experiment_generator_init_params()

        # endregion

        # region Decide whether to save the data in "CartPole memory" or not
        self.save_history = save_history_init
        self.show_experiment_summary = show_experiment_summary_init
        if self.save_history or self.show_experiment_summary:
            self.CartPoleInstance.save_data_in_cart = True
        else:
            self.CartPoleInstance.save_data_in_cart = False

        # endregion

        # region Other variables initial values as provided in gui_default_parameters.py

        # Start user controlled experiment/ start random experiment/ load and replay - on start button
        self.simulator_mode = simulator_mode_init
        self.slider_on_click = slider_on_click_init  # Update slider on click/update slider while hoovering over it
        self.speedup = speedup_init  # Default simulation speed-up

        # endregion

        # region Initialize loop-timer
        # This timer allows to relate the simulation time to user time
        # And (if your computer is fast enough) run simulation
        # slower or faster than real-time by predefined factor (speedup)
        self.looper = loop_timer(
            dt_target=(self.CartPoleInstance.dt_simulation / self.speedup))
        # endregion

        # region Variables controlling the state of various processes (DO NOT MODIFY)

        self.terminate_experiment_or_replay_thread = False  # True: gives signal causing thread to terminate
        self.pause_experiment_or_replay_thread = False  # True: gives signal causing the thread to pause

        self.run_set_labels_thread = True  # True if gauges (labels) keep being repeatedly updated
        # Stop threads by setting False

        # Flag indicating if the "START! / STOP!" button should act as start or as stop when pressed.
        # Can take values "START!" or "STOP!"
        self.start_or_stop_action = "START!"
        # Flag indicating whether the pause button should pause or unpause.
        self.pause_or_unpause_action = "PAUSE"

        # Flag indicating that saving of experiment recording to csv file has finished
        self.experiment_or_replay_thread_terminated = False

        self.user_time_counter = 0  # Measures the user time

        # Slider instant value (which is draw in GUI) differs from value saved in CartPole instance
        # if the option updating slider "on-click" is enabled.
        self.slider_instant_value = self.CartPoleInstance.slider_value

        self.noise = 'OFF'
        self.CartPoleInstance.NoiseAdderInstance.noise_mode = self.noise

        # endregion

        # region Create GUI Layout

        # region - Create container for top level layout
        layout = QVBoxLayout()
        # endregion

        # region - Change geometry of the main window
        self.setGeometry(300, 300, 2500, 1000)
        # endregion

        # region - Matplotlib figures (CartPole drawing and Slider)
        # Draw Figure
        self.fig = Figure(
            figsize=(25, 10)
        )  # Regulates the size of Figure in inches, before scaling to window size.
        self.canvas = FigureCanvas(self.fig)
        self.fig.AxCart = self.canvas.figure.add_subplot(211)
        self.fig.AxSlider = self.canvas.figure.add_subplot(212)
        self.fig.AxSlider.set_ylim(0, 1)

        self.CartPoleInstance.draw_constant_elements(self.fig, self.fig.AxCart,
                                                     self.fig.AxSlider)

        # Attach figure to the layout
        lf = QVBoxLayout()
        lf.addWidget(self.canvas)

        # endregion

        # region - Radio buttons selecting current controller
        self.rbs_controllers = []
        for controller_name in self.CartPoleInstance.controller_names:
            self.rbs_controllers.append(QRadioButton(controller_name))

        # Ensures that radio buttons are exclusive
        self.controllers_buttons_group = QButtonGroup()
        for button in self.rbs_controllers:
            self.controllers_buttons_group.addButton(button)

        lr_c = QVBoxLayout()
        lr_c.addStretch(1)
        for rb in self.rbs_controllers:
            rb.clicked.connect(self.RadioButtons_controller_selection)
            lr_c.addWidget(rb)
        lr_c.addStretch(1)

        self.rbs_controllers[self.CartPoleInstance.controller_idx].setChecked(
            True)

        # endregion

        # region - Create central part of the layout for figures and radio buttons and add it to the whole layout
        lc = QHBoxLayout()
        lc.addLayout(lf)
        lc.addLayout(lr_c)
        layout.addLayout(lc)

        # endregion

        # region - Gauges displaying current values of various states and parameters (time, velocity, angle,...)

        # First row
        ld = QHBoxLayout()
        # User time
        self.labTime = QLabel("User's time (s): ")
        self.timer = QTimer()
        self.timer.setInterval(100)  # Tick every 1/10 of the second
        self.timer.timeout.connect(self.set_user_time_label)
        self.timer.start()
        ld.addWidget(self.labTime)
        # Speed, angle, motor power (Q)
        self.labSpeed = QLabel('Speed (m/s):')
        self.labAngle = QLabel('Angle (deg):')
        self.labMotor = QLabel('')
        self.labTargetPosition = QLabel('')
        ld.addWidget(self.labSpeed)
        ld.addWidget(self.labAngle)
        ld.addWidget(self.labMotor)
        ld.addWidget(self.labTargetPosition)
        layout.addLayout(ld)

        # Second row of labels
        # Simulation time, Measured (real) speed-up, slider-value
        ld2 = QHBoxLayout()
        self.labTimeSim = QLabel('Simulation Time (s):')
        ld2.addWidget(self.labTimeSim)
        self.labSpeedUp = QLabel('Speed-up (measured):')
        ld2.addWidget(self.labSpeedUp)
        self.labSliderInstant = QLabel('')
        ld2.addWidget(self.labSliderInstant)
        layout.addLayout(ld2)

        # endregion

        # region - Buttons "START!" / "STOP!", "PAUSE", "QUIT"
        self.bss = QPushButton("START!")
        self.bss.pressed.connect(self.start_stop_button)
        self.bp = QPushButton("PAUSE")
        self.bp.pressed.connect(self.pause_unpause_button)
        bq = QPushButton("QUIT")
        bq.pressed.connect(self.quit_application)
        lspb = QHBoxLayout()  # Sub-Layout for Start/Stop and Pause Buttons
        lspb.addWidget(self.bss)
        lspb.addWidget(self.bp)

        # endregion

        # region - Sliders setting initial state and buttons for kicking the pole

        # Sliders setting initial position and angle
        lb = QVBoxLayout()  # Layout for buttons
        lb.addLayout(lspb)
        lb.addWidget(bq)
        ip = QHBoxLayout()  # Layout for initial position sliders
        self.initial_position_slider = QSlider(
            orientation=Qt.Orientation.Horizontal)
        self.initial_position_slider.setRange(
            -int(float(1000 * TrackHalfLength)),
            int(float(1000 * TrackHalfLength)))
        self.initial_position_slider.setValue(0)
        self.initial_position_slider.setSingleStep(1)
        self.initial_position_slider.valueChanged.connect(
            self.update_initial_position)
        self.initial_angle_slider = QSlider(
            orientation=Qt.Orientation.Horizontal)
        self.initial_angle_slider.setRange(-int(float(100 * np.pi)),
                                           int(float(100 * np.pi)))
        self.initial_angle_slider.setValue(0)
        self.initial_angle_slider.setSingleStep(1)
        self.initial_angle_slider.valueChanged.connect(
            self.update_initial_angle)
        ip.addWidget(QLabel("Initial position:"))
        ip.addWidget(self.initial_position_slider)
        ip.addWidget(QLabel("Initial angle:"))
        ip.addWidget(self.initial_angle_slider)
        ip.addStretch(0.01)

        # Slider setting latency
        self.LATENCY_SLIDER_RANGE_INT = 1000
        self.latency_slider = QSlider(orientation=Qt.Orientation.Horizontal)
        self.latency_slider.setRange(0, self.LATENCY_SLIDER_RANGE_INT)
        self.latency_slider.setValue(
            int(self.CartPoleInstance.LatencyAdderInstance.latency *
                self.LATENCY_SLIDER_RANGE_INT /
                self.CartPoleInstance.LatencyAdderInstance.max_latency))
        self.latency_slider.setSingleStep(1)
        self.latency_slider.valueChanged.connect(self.update_latency)
        ip.addWidget(QLabel("Latency:"))
        ip.addWidget(self.latency_slider)
        self.labLatency = QLabel('Latency (ms): {:.1f}'.format(
            self.CartPoleInstance.LatencyAdderInstance.latency * 1000))
        ip.addWidget(self.labLatency)

        # Buttons activating noise
        self.rbs_noise = []
        for mode_name in ['ON', 'OFF']:
            self.rbs_noise.append(QRadioButton(mode_name))

        # Ensures that radio buttons are exclusive
        self.noise_buttons_group = QButtonGroup()
        for button in self.rbs_noise:
            self.noise_buttons_group.addButton(button)

        lr_n = QHBoxLayout()
        lr_n.addWidget(QLabel('Noise:'))
        for rb in self.rbs_noise:
            rb.clicked.connect(self.RadioButtons_noise_on_off)
            lr_n.addWidget(rb)

        self.rbs_noise[1].setChecked(True)

        ip.addStretch(0.01)
        ip.addLayout(lr_n)
        ip.addStretch(0.01)

        # Buttons giving kick to the pole
        kick_label = QLabel("Kick pole:")
        kick_left_button = QPushButton()
        kick_left_button.setText("Left")
        kick_left_button.adjustSize()
        kick_left_button.clicked.connect(self.kick_pole)
        kick_right_button = QPushButton()
        kick_right_button.setText("Right")
        kick_right_button.adjustSize()
        kick_right_button.clicked.connect(self.kick_pole)
        ip.addWidget(kick_label)
        ip.addWidget(kick_left_button)
        ip.addWidget(kick_right_button)

        lb.addLayout(ip)
        layout.addLayout(lb)

        # endregion

        # region - Text boxes and Combobox to provide settings concerning generation of random experiment
        l_generate_trace = QHBoxLayout()
        l_generate_trace.addWidget(QLabel('Random experiment settings:'))
        l_generate_trace.addWidget(QLabel('Length (s):'))
        self.textbox_length = QLineEdit()
        l_generate_trace.addWidget(self.textbox_length)
        l_generate_trace.addWidget(QLabel('Turning Points (m):'))
        self.textbox_turning_points = QLineEdit()
        l_generate_trace.addWidget(self.textbox_turning_points)
        l_generate_trace.addWidget(QLabel('Interpolation:'))
        self.cb_interpolation = QComboBox()
        self.cb_interpolation.addItems(
            ['0-derivative-smooth', 'linear', 'previous'])
        self.cb_interpolation.currentIndexChanged.connect(
            self.cb_interpolation_selectionchange)
        self.cb_interpolation.setCurrentText(
            self.CartPoleInstance.interpolation_type)
        l_generate_trace.addWidget(self.cb_interpolation)

        layout.addLayout(l_generate_trace)

        # endregion

        # region - Textbox to provide csv file name for saving or loading data
        l_text = QHBoxLayout()
        textbox_title = QLabel('CSV file name:')
        self.textbox = QLineEdit()
        l_text.addWidget(textbox_title)
        l_text.addWidget(self.textbox)
        layout.addLayout(l_text)

        # endregion

        # region - Make strip of layout for checkboxes
        l_cb = QHBoxLayout()
        # endregion

        # region - Textbox to provide the target speed-up value
        l_text_speedup = QHBoxLayout()
        tx_speedup_title = QLabel('Speed-up (target):')
        self.tx_speedup = QLineEdit()
        l_text_speedup.addWidget(tx_speedup_title)
        l_text_speedup.addWidget(self.tx_speedup)
        self.tx_speedup.setText(str(self.speedup))
        l_cb.addLayout(l_text_speedup)

        self.wrong_speedup_msg = QMessageBox()
        self.wrong_speedup_msg.setWindowTitle("Speed-up value problem")
        self.wrong_speedup_msg.setIcon(QMessageBox.Icon.Critical)
        # endregion

        # region - Checkboxes

        # region -- Checkbox: Save/don't save experiment recording
        self.cb_save_history = QCheckBox('Save results', self)
        if self.save_history:
            self.cb_save_history.toggle()
        self.cb_save_history.toggled.connect(self.cb_save_history_f)
        l_cb.addWidget(self.cb_save_history)
        # endregion

        # region -- Checkbox: Display plots showing dynamic evolution of the system as soon as experiment terminates
        self.cb_show_experiment_summary = QCheckBox('Show experiment summary',
                                                    self)
        if self.show_experiment_summary:
            self.cb_show_experiment_summary.toggle()
        self.cb_show_experiment_summary.toggled.connect(
            self.cb_show_experiment_summary_f)
        l_cb.addWidget(self.cb_show_experiment_summary)
        # endregion

        # region -- Checkbox: Block pole if it reaches +/-90 deg
        self.cb_stop_at_90_deg = QCheckBox('Stop-at-90-deg', self)
        if self.CartPoleInstance.stop_at_90:
            self.cb_stop_at_90_deg.toggle()
        self.cb_stop_at_90_deg.toggled.connect(self.cb_stop_at_90_deg_f)
        l_cb.addWidget(self.cb_stop_at_90_deg)
        # endregion

        # region -- Checkbox: Update slider on click/update slider while hoovering over it
        self.cb_slider_on_click = QCheckBox('Update slider on click', self)
        if self.slider_on_click:
            self.cb_slider_on_click.toggle()
        self.cb_slider_on_click.toggled.connect(self.cb_slider_on_click_f)
        l_cb.addWidget(self.cb_slider_on_click)

        # endregion

        # endregion

        # region - Radio buttons selecting simulator mode: user defined experiment, random experiment, replay

        # List available simulator modes - constant
        self.available_simulator_modes = [
            'Slider-Controlled Experiment', 'Random Experiment', 'Replay'
        ]
        self.rbs_simulator_mode = []
        for mode_name in self.available_simulator_modes:
            self.rbs_simulator_mode.append(QRadioButton(mode_name))

        # Ensures that radio buttons are exclusive
        self.simulator_mode_buttons_group = QButtonGroup()
        for button in self.rbs_simulator_mode:
            self.simulator_mode_buttons_group.addButton(button)

        lr_sm = QHBoxLayout()
        lr_sm.addStretch(1)
        lr_sm.addWidget(QLabel('Simulator mode:'))
        for rb in self.rbs_simulator_mode:
            rb.clicked.connect(self.RadioButtons_simulator_mode)
            lr_sm.addWidget(rb)
        lr_sm.addStretch(1)

        self.rbs_simulator_mode[self.available_simulator_modes.index(
            self.simulator_mode)].setChecked(True)

        l_cb.addStretch(1)
        l_cb.addLayout(lr_sm)
        l_cb.addStretch(1)

        # endregion

        # region - Add checkboxes to layout
        layout.addLayout(l_cb)
        # endregion

        # region - Create an instance of a GUI window
        w = QWidget()
        w.setLayout(layout)
        self.setCentralWidget(w)
        self.show()
        self.setWindowTitle('CartPole Simulator')

        # endregion

        # endregion

        # region Open controller-specific popup windows
        self.open_additional_controller_widget()
        # endregion

        # region Activate functions capturing mouse movements and clicks over the slider

        # This line links function capturing the mouse position on the canvas of the Figure
        self.canvas.mpl_connect("motion_notify_event", self.on_mouse_movement)
        # This line links function capturing the mouse position on the canvas of the Figure click
        self.canvas.mpl_connect("button_press_event", self.on_mouse_click)

        # endregion

        # region Introducing multithreading
        # To ensure smooth functioning of the app,
        # the calculations and redrawing of the figures have to be done in a different thread
        # than the one capturing the mouse position and running the animation
        self.threadpool = QThreadPool()
        # endregion

        # region Starts a thread repeatedly redrawing gauges (labels) of the GUI
        # It runs till the QUIT button is pressed
        worker_labels = Worker(self.set_labels_thread)
        self.threadpool.start(worker_labels)
        # endregion

        # region Start animation repeatedly redrawing changing elements of matplotlib figures (CartPole drawing and slider)
        # This animation runs ALWAYS when the GUI is open
        # The buttons of GUI only decide if new parameters are calculated or not
        self.anim = self.CartPoleInstance.run_animation(self.fig)
Exemple #24
0
    def __init__(self):
        super(NoiseOptionsWindow, self).__init__()

        self.sigma_angle = noise_settings.sigma_angle
        self.sigma_position = noise_settings.sigma_position

        self.sigma_angleD = noise_settings.sigma_angleD
        self.sigma_positionD = noise_settings.sigma_positionD

        layout = QVBoxLayout()

        self.setLayout(layout)
        self.setWindowFlags(self.windowFlags() | Qt.WindowType.WindowStaysOnTopHint)
        self.setGeometry(0, 0, 400, 50)

        sigmas_layout = QVBoxLayout()

        def make_slider(MAX_RANGE, INIT_VALUE):
            label = QLabel("")
            label.setAlignment(Qt.AlignmentFlag.AlignCenter)

            slider = QSlider(orientation=Qt.Orientation.Horizontal)
            slider.setRange(0, SLIDER_MAX_RANGE_INT)
            slider.setValue(int(SLIDER_MAX_RANGE_INT*(INIT_VALUE/MAX_RANGE)))
            slider.setTickPosition(QSlider.TickPosition.TicksBelow)
            slider.setTickInterval(int(SLIDER_MAX_RANGE_INT*0.1))
            slider.setSingleStep(1)

            return slider, label

        self.slider_angle, self.sigma_angle_label = make_slider(MAX_RANGE=NOISE_STD_MAX_RANGE,
                                                     INIT_VALUE=self.sigma_angle)
        sigmas_layout.addWidget(self.sigma_angle_label)
        sigmas_layout.addWidget(self.slider_angle)
        self.slider_angle.valueChanged.connect(self.sigma_angle_changed)

        self.slider_position, self.sigma_position_label = make_slider(MAX_RANGE=NOISE_STD_MAX_RANGE,
                                                     INIT_VALUE=self.sigma_position)
        sigmas_layout.addWidget(self.sigma_position_label)
        sigmas_layout.addWidget(self.slider_position)
        self.slider_position.valueChanged.connect(self.sigma_position_changed)



        self.slider_angleD, self.sigma_angleD_label = make_slider(MAX_RANGE=NOISE_STD_MAX_RANGE,
                                                     INIT_VALUE=self.sigma_angleD)
        sigmas_layout.addWidget(self.sigma_angleD_label)
        sigmas_layout.addWidget(self.slider_angleD)
        self.slider_angleD.valueChanged.connect(self.sigma_angleD_changed)

        self.slider_positionD, self.sigma_positionD_label = make_slider(MAX_RANGE=NOISE_STD_MAX_RANGE,
                                                        INIT_VALUE=self.sigma_positionD)
        sigmas_layout.addWidget(self.sigma_positionD_label)
        sigmas_layout.addWidget(self.slider_positionD)
        self.slider_positionD.valueChanged.connect(self.sigma_positionD_changed)



        self.update_slider_labels()
        layout.addLayout(sigmas_layout)

        self.show()
        self.setWindowTitle("Noise Options")
Exemple #25
0
 def __init__(self):
     super().__init__()
     self.setWindowTitle('GitHub Abuz!')
     self.setWindowIcon(QIcon('icon.png'))
     layout = QGridLayout()
     vl = QVBoxLayout()
     hl = QHBoxLayout()
     hl2 = QHBoxLayout()
     hl3 = QHBoxLayout()
     self.y = QComboBox()
     self.name = QLineEdit()
     self.email = QLineEdit()
     self.passw = QLineEdit()
     self.repo = QLineEdit()
     self.type = QLineEdit()
     self.fonts = QComboBox()
     self.err = QMessageBox()
     self.nc = QSpinBox()
     lbl = QLabel('Commits/day:')
     prev = QPushButton('Translate')
     invert = QPushButton('Invert')
     leggo = QPushButton('Do it')
     invert.clicked.connect(self.invert)
     leggo.clicked.connect(self.doit)
     prev.clicked.connect(self.textCheck)
     self.name.textChanged[str].connect(self.rmph)
     self.email.textChanged[str].connect(self.rmph)
     self.passw.textChanged[str].connect(self.rmph)
     self.type.textChanged[str].connect(self.rmph)
     self.repo.textChanged[str].connect(self.rmph)
     self.y.addItem('Year (default: last 52 weeks)')
     for yr in range(datetime.datetime.now().year + 5,
                     datetime.datetime.now().year - 20, -1):
         self.y.addItem(str(yr))
     self.fonts.addItems(os.listdir('Fonts'))
     self.name.setPlaceholderText('Committer name')
     self.email.setPlaceholderText('Committer email')
     self.passw.setPlaceholderText('Password')
     self.passw.setEchoMode(QLineEdit.EchoMode.Password)
     self.repo.setPlaceholderText('Link to repo')
     self.type.setPlaceholderText('Translate text to tile art!')
     self.nc.setMinimum(1)
     self.nc.setValue(1)
     self.err.setWindowIcon(QIcon('icon.png'))
     self.err.setWindowTitle('Error!')
     hl.addWidget(self.name)
     hl.addWidget(self.email)
     hl.addWidget(self.passw)
     hl3.addWidget(self.repo)
     hl3.addWidget(self.y)
     hl3.addWidget(lbl)
     hl3.addWidget(self.nc)
     hl2.addWidget(self.type)
     hl2.addWidget(self.fonts)
     hl2.addWidget(prev)
     hl2.addWidget(invert)
     vl.addLayout(hl)
     vl.addLayout(hl3)
     vl.addLayout(layout)
     vl.addLayout(hl2)
     vl.addWidget(leggo)
     self.setLayout(vl)
     self.checkM = [list() for i in range(7)]
     for i in range(7):
         for j in range(52):
             m = QCheckBox()
             layout.addWidget(m, i, j)
             self.checkM[i].append(m)
Exemple #26
0
class ConfigDialog(QDialog):
    def __init__(self, parent=None):
        super(ConfigDialog, self).__init__(parent)
        self.classifyExercises = parent.classifyExercises
        self.setFixedSize(500, 400)
        self.setWindowTitle("Model Configurations")

        self.epochValue = QLabel()
        self.vbox = QVBoxLayout()
        self.label_maximum = QLabel()
        self.label_minimum = QLabel()
        self.slider_hbox = QHBoxLayout()
        self.slider_vbox = QVBoxLayout()
        self.batchSizeMenu = QComboBox()
        self.properties = QFormLayout()
        self.epochSlider = Slider(orientation=Qt.Orientations.Horizontal)

        self.trainButton = QPushButton('Train Model')
        self.resultButton = QPushButton('Show result image')
        self.progress = QProgressBar()

        self.batchSizeMenu.addItems(['2', '4', '8', '16', '32', '64', '128'])
        self.batchSizeMenu.setCurrentIndex(3)
        self.batchSizeMenu.setMaximumWidth(100)

        self.initSlider()

        self.properties.addRow('Batch Size', self.batchSizeMenu)

        self.resultButton.setEnabled(False)
        self.actionsLayout = QHBoxLayout()

        self.actionsLayout.addWidget(self.trainButton)
        self.actionsLayout.addWidget(self.resultButton)

        self.optionsLayout = QVBoxLayout()
        self.optionsLayout.addWidget(QLabel('Model properties'))
        self.optionsLayout.addLayout(self.vbox)
        self.optionsLayout.addLayout(self.properties)
        self.optionsLayout.addLayout(self.actionsLayout)
        self.progress.setAlignment(QtCore.Qt.Alignment.AlignCenter)
        self.optionsLayout.addWidget(self.progress)
        # self.options_layout.addWidget(self.label)
        # self.options_layout.addWidget(self.list_widget)

        self.setLayout(self.optionsLayout)

        self.trainThread = TrainThread(self.classifyExercises)
        self.connections()
        print("init config")

    def initSlider(self):
        self.epochValue.setAlignment(QtCore.Qt.Alignment.AlignHCenter)

        self.epochSlider.setMinimum(2)
        self.epochSlider.setMaximum(10)
        self.epochSlider.setTickInterval(1)
        # self.epochSlider.setInterval(1)
        # self.epochSlider.setValue(8)  # no idea why, but 8 is the middle somehow
        self.epochSlider.setSliderPosition(6)
        self.epochSlider.setTickPosition(QSlider.TickPosition.TicksBelow)

        self.label_minimum.setNum(self.epochSlider.minimum().real * 50)
        self.label_minimum.setAlignment(QtCore.Qt.Alignment.AlignLeft)
        self.label_maximum.setNum(self.epochSlider.maximum().real * 50)

        self.label_maximum.setAlignment(QtCore.Qt.Alignment.AlignRight)

        self.epochSlider.minimumChanged.connect(self.label_minimum.setNum)
        self.epochSlider.maximumChanged.connect(self.label_maximum.setNum)

        self.slider_hbox.addWidget(self.label_minimum,
                                   QtCore.Qt.Alignment.AlignLeft)
        self.slider_hbox.addWidget(self.epochValue)
        self.slider_hbox.addWidget(self.label_maximum,
                                   QtCore.Qt.Alignment.AlignRight)

        self.slider_vbox.addWidget(self.epochSlider)
        self.slider_vbox.addLayout(self.slider_hbox)
        # self.slider_vbox.addStretch()

        self.vbox.addLayout(self.slider_vbox)

    def connections(self):
        self.batchSizeMenu.currentIndexChanged.connect(
            self.onBatchSizeSelected)
        self.resultButton.clicked.connect(self.onResultClicked)
        self.trainButton.clicked.connect(self.onTrainClicked)
        self.epochSlider.valueChanged.connect(self.updateEpochValue)
        self.trainThread.taskFinished.connect(self.onFinished)

    def updateEpochValue(self, num):
        print(num)
        epochs = num * 50
        self.epochValue.setNum(epochs)
        self.classifyExercises.epochs = epochs

    def onBatchSizeSelected(self, ind):
        self.classifyExercises.training_batch_size = int(
            self.batchSizeMenu.currentText())

    def onResultClicked(self):
        print("open image")
        self.classifyExercises.DisplayResults()

    def onTrainClicked(self):
        if self.classifyExercises.subject is not None:
            if self.classifyExercises.DataAvailable():
                if self.resultButton.isEnabled:
                    self.resultButton.setEnabled(False)

                self.trainThread.start()
                self.progress.setRange(0, 0)
            else:
                CustomMessage.showDialog(
                    "Message", "Calibrate for patient to obtain data.",
                    QMessageBox.StandardButtons.Ok)

        else:
            CustomMessage.showDialog(
                "Message", "You must either select or enter a subject name.",
                QMessageBox.StandardButtons.Ok)
            print("Subject is none!")

    def onFinished(self):
        # Stop the progress
        self.progress.setRange(0, 1)
        self.progress.setValue(1)
        CustomMessage.showDialog("Message", "Training model finished!",
                                 QMessageBox.StandardButtons.Ok)
        self.resultButton.setEnabled(True)
Exemple #27
0
    def __init__(self):
        super().__init__()
        # setup some flags
        self.isFetching = False
        self.isDownloading = False

        # default output path
        self.outputPath = f'{QDir.homePath()}/videos'

        # setup some window specific things
        self.setWindowTitle('YouTube Downloader')
        self.setWindowIcon(QIcon('assets/yt-icon.ico'))
        self.setFixedSize(705, 343)

        # parent layout
        layout = QVBoxLayout()
        layout.setContentsMargins(15, 15, 15, 10)
        self.setLayout(layout)

        # top bar layout
        topBar = QHBoxLayout()

        # detail section
        detailSec = QHBoxLayout()
        metaSec = QVBoxLayout()

        # download section
        downloadSec = QHBoxLayout()
        downloadBtn = QVBoxLayout()

        # output path link button
        self.outputBtn = QPushButton('📂  Output Path')
        self.outputBtn.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.outputBtn.setToolTip(self.outputPath)
        self.outputBtn.clicked.connect(self.setOutputPath)

        # status bar
        self.statusBar = QStatusBar()

        # message box
        self.message = QMessageBox()

        # setting up widgets
        self.urlBox = QLineEdit()
        self.urlBox.setFocusPolicy(Qt.FocusPolicy.ClickFocus or Qt.FocusPolicy.NoFocus)
        self.urlBox.setPlaceholderText('🔍 Enter or paste video URL...')
        self.button = QPushButton('Get')
        self.button.setDefault(True)
        self.button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.button.clicked.connect(self.getDetails)

        # thumbnail
        pixmap = QPixmap('assets\placeholder.jpg')
        self.thumb = QLabel()
        self.thumb.setFixedSize(250, 141)
        self.thumb.setScaledContents(True)
        self.thumb.setPixmap(pixmap)

        # detail widgets
        self.title = QLabel('Title: ')
        self.author = QLabel('Author: ')
        self.length = QLabel('Duration: ')
        self.publish_date = QLabel('Published: ')

        # progress bar
        self.progress_bar = QProgressBar()
        
        # download options
        self.download = QComboBox()
        self.download.setPlaceholderText('Download Video')
        self.download.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.download.activated.connect(lambda: self.getContent(0))
        self.download.setEnabled(False)

        # download audio button
        self.download_audio = QPushButton('Download Audio')
        self.download_audio.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.download_audio.clicked.connect(lambda: self.getContent(1))
        self.download_audio.setEnabled(False)

        # add widgets and layouts
        topBar.addWidget(self.urlBox)
        topBar.addWidget(self.button)

        # detail section
        metaSec.addWidget(self.title)
        metaSec.addWidget(self.author)
        metaSec.addWidget(self.length)
        metaSec.addWidget(self.publish_date)
        detailSec.addWidget(self.thumb)
        detailSec.addSpacing(20)
        detailSec.addLayout(metaSec)

        # download section
        downloadBtn.addWidget(self.download)
        downloadBtn.addWidget(self.download_audio)
        downloadSec.addWidget(self.progress_bar)
        downloadSec.addSpacing(10)
        downloadSec.addLayout(downloadBtn)

        # status bar
        self.statusBar.setSizeGripEnabled(False)
        self.statusBar.addPermanentWidget(self.outputBtn)

        # add content to parent layout
        layout.addLayout(topBar)
        layout.addSpacing(20)
        layout.addLayout(detailSec)
        layout.addSpacing(5)
        layout.addLayout(downloadSec)
        layout.addWidget(self.statusBar)

        # setup a connection thread to keep checking internet connectivity
        self.connection = ConnectionThread()
        self.connection.start()

        # catch the connection response signal
        self.connection.con_response.connect(self.connection_slot)
Exemple #28
0
    def __init__(self):
        super(B23Download, self).__init__()
        # setup some flags
        self.is_fetching = False
        self.is_downloading = False

        # default output path
        basepath = os.path.dirname(os.path.abspath(__file__))
        path = os.path.join(basepath, "videos")
        self.output_path = path

        # setup some window specific things
        self.setWindowTitle("Bilibili Favorite Downloader")
        self.setWindowIcon(QIcon("images/icon_bilibili.ico"))
        self.setFixedSize(705, 343)

        # parent layout
        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(15, 15, 15, 10)
        self.setLayout(main_layout)

        # top bar layout
        top_layout = QHBoxLayout()

        # detail section
        mid_main_layout = QHBoxLayout()
        mid_right_layout = QVBoxLayout()

        # download section
        bottom_main_layout = QHBoxLayout()
        bottom_right_layout = QVBoxLayout()

        # output path link button
        self.output_btn = QPushButton("📂  Output Path")
        self.output_btn.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.output_btn.setToolTip(self.output_path)
        self.output_btn.clicked.connect(self.set_output_path)

        # status bar
        self.status_bar = QStatusBar()

        # message box
        self.message_box = QMessageBox()

        # setting up widgets
        self.url_edit = QLineEdit()
        self.url_edit.setPlaceholderText("🔍 Enter or paste favorite URL...")
        self.get_btn = QPushButton("Get")
        self.get_btn.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.get_btn.clicked.connect(self.get_details)

        # thumbnail
        pixmap = QPixmap("images/placeholder.png")
        self.thumb = QLabel()
        self.thumb.setFixedSize(250, 141)
        self.thumb.setScaledContents(True)
        self.thumb.setPixmap(pixmap)

        # detail widgets
        self.title = QLabel("Title: ")
        self.author = QLabel("Author: ")
        self.length = QLabel("Videos: ")
        self.publish_date = QLabel("Published: ")

        # progress bar
        self.progress_bar = QProgressBar()

        # download options
        self.download_btn = QPushButton(" Download Videos ")
        self.download_btn.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.download_btn.clicked.connect(self.get_content)
        self.download_btn.setEnabled(False)
        self.download_btn.setShortcut("Ctrl+Return")
        self.download_btn.setMinimumWidth(200)

        # add widgets and layouts
        top_layout.addWidget(self.url_edit)
        top_layout.addWidget(self.get_btn)

        # detail section
        mid_right_layout.addWidget(self.title)
        mid_right_layout.addWidget(self.author)
        mid_right_layout.addWidget(self.length)
        mid_right_layout.addWidget(self.publish_date)
        mid_main_layout.addWidget(self.thumb)
        mid_main_layout.addSpacing(20)
        mid_main_layout.addLayout(mid_right_layout)

        # download section
        bottom_right_layout.addWidget(self.download_btn)
        bottom_main_layout.addWidget(self.progress_bar)
        bottom_main_layout.addSpacing(10)
        bottom_main_layout.addLayout(bottom_right_layout)

        # status bar
        self.status_bar.setSizeGripEnabled(False)
        self.status_bar.addPermanentWidget(self.output_btn)

        # add content to parent layout
        main_layout.addLayout(top_layout)
        main_layout.addSpacing(20)
        main_layout.addLayout(mid_main_layout)
        main_layout.addSpacing(5)
        main_layout.addLayout(bottom_main_layout)
        main_layout.addWidget(self.status_bar)
Exemple #29
0
    def initUI(self):
        self.setWindowTitle("设置")
        logo = QLabel()
        logo.setPixmap(QPixmap(SRC_DIR + "logo2.gif"))
        logo.setStyleSheet("background-color:rgb(255,255,255);")
        logo.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.download_threads_lb = QLabel("同时下载文件数")
        self.download_threads_var = QLineEdit()
        self.download_threads_var.setPlaceholderText("范围:1-9")
        self.download_threads_var.setToolTip("范围:1-9")
        self.download_threads_var.setInputMask("D")
        self.max_size_lb = QLabel("分卷大小(MB)")
        self.max_size_var = QLineEdit()
        self.max_size_var.setPlaceholderText("普通用户最大100,vip用户根据具体情况设置")
        self.max_size_var.setToolTip("普通用户最大100,vip用户根据具体情况设置")
        self.max_size_var.setInputMask("D99")
        self.timeout_lb = QLabel("请求超时(秒)")
        self.timeout_var = QLineEdit()
        self.timeout_var.setPlaceholderText("范围:1-99")
        self.timeout_var.setToolTip("范围:1-99")
        self.timeout_var.setInputMask("D9")
        self.upload_delay_lb = QLabel("上传延时(秒)")
        self.upload_delay_var = QLineEdit()
        self.upload_delay_var.setPlaceholderText("范围:1-99")
        self.upload_delay_var.setToolTip("范围:1-99")
        self.upload_delay_var.setInputMask("D9")
        self.dl_path_lb = QLabel("下载保存路径")
        self.dl_path_var = MyLineEdit(self)
        self.dl_path_var.clicked.connect(self.set_download_path)
        self.time_fmt_box = QCheckBox("使用[年-月-日]时间格式")
        self.time_fmt_box.setToolTip("文件上传日期显示格式")
        self.to_tray_box = QCheckBox("关闭到系统托盘")
        self.to_tray_box.setToolTip("点击关闭软件按钮是最小化软件至系统托盘")
        self.watch_clipboard_box = QCheckBox("监听系统剪切板")
        self.watch_clipboard_box.setToolTip("检测到系统剪切板中有符合规范的蓝奏链接时自动唤起软件,并提取")
        self.debug_box = QCheckBox("开启调试日志")
        self.debug_box.setToolTip("记录软件 debug 信息至 debug-lanzou-gui.log 文件")
        self.set_pwd_box = QCheckBox("上传文件自动设置密码")
        self.set_pwd_var = AutoResizingTextEdit()
        self.set_pwd_var.setPlaceholderText(" 2-8 位数字或字母")
        self.set_pwd_var.setToolTip("2-8 位数字或字母")
        self.set_desc_box = QCheckBox("上传文件自动设置描述")
        self.set_desc_var = AutoResizingTextEdit()
        self.big_file_box = QCheckBox(f"允许上传超过 {self.max_size}MB 的大文件")
        self.big_file_box.setToolTip("开启大文件上传支持 (功能下线)")
        self.upgrade_box = QCheckBox("自动检测新版本")
        self.upgrade_box.setToolTip("在软件打开时自动检测是否有新的版本发布,如有则弹出更新信息")

        self.time_fmt_box.toggle()
        self.time_fmt_box.stateChanged.connect(self.change_time_fmt)
        self.to_tray_box.stateChanged.connect(self.change_to_tray)
        self.watch_clipboard_box.stateChanged.connect(self.change_watch_clipboard)
        self.debug_box.stateChanged.connect(self.change_debug)
        self.set_pwd_box.stateChanged.connect(self.change_set_pwd)
        self.set_pwd_var.editingFinished.connect(self.check_pwd)
        self.set_desc_box.stateChanged.connect(self.change_set_desc)
        self.big_file_box.stateChanged.connect(self.change_big_file)
        self.upgrade_box.stateChanged.connect(self.change_upgrade)

        buttonBox = QDialogButtonBox()
        buttonBox.setOrientation(Qt.Orientation.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.StandardButton.Reset | QDialogButtonBox.StandardButton.Save | QDialogButtonBox.StandardButton.Cancel)
        buttonBox.button(QDialogButtonBox.StandardButton.Reset).setText("重置")
        buttonBox.button(QDialogButtonBox.StandardButton.Save).setText("保存")
        buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setText("取消")
        buttonBox.button(QDialogButtonBox.StandardButton.Reset).clicked.connect(lambda: self.set_values(reset=True))
        buttonBox.button(QDialogButtonBox.StandardButton.Save).clicked.connect(self.slot_save)
        buttonBox.rejected.connect(self.reject)

        form = QFormLayout()
        form.setLabelAlignment(Qt.AlignmentFlag.AlignRight)
        form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)  # 覆盖MacOS的默认样式
        form.setSpacing(10)
        form.addRow(self.download_threads_lb, self.download_threads_var)
        form.addRow(self.timeout_lb, self.timeout_var)
        form.addRow(self.upload_delay_lb, self.upload_delay_var)
        form.addRow(self.max_size_lb, self.max_size_var)
        form.addRow(self.dl_path_lb, self.dl_path_var)

        vbox = QVBoxLayout()
        vbox.addWidget(logo)
        vbox.addStretch(1)
        vbox.addLayout(form)
        vbox.addStretch(1)
        hbox = QHBoxLayout()
        hbox.addWidget(self.time_fmt_box)
        hbox.addWidget(self.to_tray_box)
        hbox.addWidget(self.watch_clipboard_box)
        hbox.addWidget(self.debug_box)
        vbox.addLayout(hbox)
        vbox.addStretch(1)
        hbox_2 = QHBoxLayout()
        hbox_2.addWidget(self.set_pwd_box)
        hbox_2.addWidget(self.set_pwd_var)
        vbox.addLayout(hbox_2)
        vbox.addStretch(1)
        hbox_3 = QHBoxLayout()
        hbox_3.addWidget(self.set_desc_box)
        hbox_3.addWidget(self.set_desc_var)
        vbox.addLayout(hbox_3)
        hbox_4 = QHBoxLayout()
        hbox_4.addWidget(self.big_file_box)
        hbox_4.addWidget(self.upgrade_box)
        vbox.addStretch(1)
        vbox.addLayout(hbox_4)
        vbox.addStretch(2)
        vbox.addWidget(buttonBox)
        self.setLayout(vbox)
        self.setMinimumWidth(500)
    def __init__(self):
        super(MPPIOptionsWindow, self).__init__()

        self.horizon_steps = controller_mppi.mpc_samples
        self.num_rollouts = controller_mppi.num_rollouts
        self.dd_weight = controller_mppi.dd_weight
        self.ep_weight = controller_mppi.ep_weight
        self.ekp_weight = controller_mppi.ekp_weight * 1.0e1
        self.ekc_weight = controller_mppi.ekc_weight * 1.0e-1
        self.cc_weight = controller_mppi.cc_weight * 1.0e-2
        self.ccrc_weight = controller_mppi.ccrc_weight * 1.0e-2
        self.R = controller_mppi.R  # How much to punish Q
        self.LBD = controller_mppi.LBD  # Cost parameter lambda
        self.NU = controller_mppi.NU  # Exploration variance

        layout = QVBoxLayout()

        ### Set Horizon Length
        horizon_options_layout = QVBoxLayout()

        self.horizon_label = QLabel("")
        self.horizon_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        horizon_options_layout.addWidget(self.horizon_label)

        slider = QSlider(orientation=Qt.Orientation.Horizontal)
        slider.setRange(10, 300)
        slider.setValue(self.horizon_steps)
        slider.setTickPosition(QSlider.TickPosition.TicksBelow)
        slider.setTickInterval(10)
        slider.setSingleStep(10)
        horizon_options_layout.addWidget(slider)

        slider.valueChanged.connect(self.horizon_length_changed)

        ### Set Number of Rollouts
        rollouts_options_layout = QVBoxLayout()

        self.rollouts_label = QLabel("")
        self.rollouts_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        rollouts_options_layout.addWidget(self.rollouts_label)

        slider = QSlider(orientation=Qt.Orientation.Horizontal)
        slider.setRange(10, 3000)
        slider.setValue(self.num_rollouts)
        slider.setTickPosition(QSlider.TickPosition.TicksBelow)
        slider.setTickInterval(10)
        slider.setSingleStep(10)
        rollouts_options_layout.addWidget(slider)

        slider.valueChanged.connect(self.num_rollouts_changed)

        ### Set Cost Weights
        cost_weight_layout = QVBoxLayout()

        # Distance difference cost
        self.dd_weight_label = QLabel("")
        self.dd_weight_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        cost_weight_layout.addWidget(self.dd_weight_label)
        self.dd_label = QLabel("")
        self.dd_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        cost_weight_layout.addWidget(self.dd_label)
        slider = QSlider(orientation=Qt.Orientation.Horizontal)
        slider.setRange(0, 990)
        slider.setValue(self.dd_weight)
        slider.setTickPosition(QSlider.TickPosition.TicksBelow)
        slider.setTickInterval(10)
        slider.setSingleStep(10)
        cost_weight_layout.addWidget(slider)
        slider.valueChanged.connect(self.dd_weight_changed)

        # Potential energy cost
        self.ep_weight_label = QLabel("")
        self.ep_weight_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        cost_weight_layout.addWidget(self.ep_weight_label)
        self.ep_label = QLabel("")
        self.ep_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        cost_weight_layout.addWidget(self.ep_label)
        slider = QSlider(orientation=Qt.Orientation.Horizontal)
        slider.setRange(0, 1e5 - 1e3)
        slider.setValue(self.ep_weight)
        slider.setTickPosition(QSlider.TickPosition.TicksBelow)
        slider.setTickInterval(1e3)
        slider.setSingleStep(1e3)
        cost_weight_layout.addWidget(slider)
        slider.valueChanged.connect(self.ep_weight_changed)

        # Pole kinetic energy cost
        self.ekp_weight_label = QLabel("")
        self.ekp_weight_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        cost_weight_layout.addWidget(self.ekp_weight_label)
        self.ekp_label = QLabel("")
        self.ekp_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        cost_weight_layout.addWidget(self.ekp_label)
        slider = QSlider(orientation=Qt.Orientation.Horizontal)
        slider.setRange(0, 99)
        slider.setValue(self.ekp_weight)
        slider.setTickPosition(QSlider.TickPosition.TicksBelow)
        slider.setTickInterval(1)
        slider.setSingleStep(1)
        cost_weight_layout.addWidget(slider)
        slider.valueChanged.connect(self.ekp_weight_changed)

        # Cart kinetic energy cost
        self.ekc_weight_label = QLabel("")
        self.ekc_weight_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        cost_weight_layout.addWidget(self.ekc_weight_label)
        self.ekc_label = QLabel("")
        self.ekc_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        cost_weight_layout.addWidget(self.ekc_label)
        slider = QSlider(orientation=Qt.Orientation.Horizontal)
        slider.setRange(0, 99)
        slider.setValue(self.ekc_weight)
        slider.setTickPosition(QSlider.TickPosition.TicksBelow)
        slider.setTickInterval(1)
        slider.setSingleStep(1)
        cost_weight_layout.addWidget(slider)
        slider.valueChanged.connect(self.ekc_weight_changed)

        # Control cost
        self.cc_weight_label = QLabel("")
        self.cc_weight_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        cost_weight_layout.addWidget(self.cc_weight_label)
        self.cc_label = QLabel("")
        self.cc_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        cost_weight_layout.addWidget(self.cc_label)
        slider = QSlider(orientation=Qt.Orientation.Horizontal)
        slider.setRange(0, 99)
        slider.setValue(self.cc_weight)
        slider.setTickPosition(QSlider.TickPosition.TicksBelow)
        slider.setTickInterval(1)
        slider.setSingleStep(1)
        cost_weight_layout.addWidget(slider)
        slider.valueChanged.connect(self.cc_weight_changed)

        # Control change rate cost
        self.ccrc_weight_label = QLabel("")
        self.ccrc_weight_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        cost_weight_layout.addWidget(self.ccrc_weight_label)
        self.ccrc_label = QLabel("")
        self.ccrc_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        cost_weight_layout.addWidget(self.ccrc_label)
        slider = QSlider(orientation=Qt.Orientation.Horizontal)
        slider.setRange(0, 99)
        slider.setValue(self.ccrc_weight)
        slider.setTickPosition(QSlider.TickPosition.TicksBelow)
        slider.setTickInterval(1)
        slider.setSingleStep(1)
        cost_weight_layout.addWidget(slider)
        slider.valueChanged.connect(self.ccrc_weight_changed)

        ### Set some more MPPI constants
        mppi_constants_layout = QVBoxLayout()

        # Quadratic cost penalty R
        textbox = QLineEdit()
        textbox.setText(str(self.R))
        textbox.textChanged.connect(self.R_changed)
        h_layout = QHBoxLayout()
        h_layout.addWidget(QLabel("Quadratic input cost penalty R ="))
        h_layout.addWidget(textbox)
        mppi_constants_layout.addLayout(h_layout)

        # Quadratic cost penalty LBD
        textbox = QLineEdit()
        textbox.setText(str(self.LBD))
        textbox.textChanged.connect(self.LBD_changed)
        h_layout = QHBoxLayout()
        h_layout.addWidget(QLabel("Importance of higher-cost rollouts LBD ="))
        h_layout.addWidget(textbox)
        mppi_constants_layout.addLayout(h_layout)

        # Quadratic cost penalty NU
        textbox = QLineEdit()
        textbox.setText(str(self.NU))
        textbox.textChanged.connect(self.NU_changed)
        h_layout = QHBoxLayout()
        h_layout.addWidget(QLabel("Exploration variance NU ="))
        h_layout.addWidget(textbox)
        mppi_constants_layout.addLayout(h_layout)

        # Sampling type
        h_layout = QHBoxLayout()
        btn1 = QRadioButton("iid")
        if btn1.text() == controller_mppi.SAMPLING_TYPE: btn1.setChecked(True)
        btn1.toggled.connect(lambda: self.toggle_button(btn1))
        h_layout.addWidget(btn1)
        btn2 = QRadioButton("random_walk")
        if btn2.text() == controller_mppi.SAMPLING_TYPE: btn2.setChecked(True)
        btn2.toggled.connect(lambda: self.toggle_button(btn2))
        h_layout.addWidget(btn2)
        btn3 = QRadioButton("uniform")
        if btn3.text() == controller_mppi.SAMPLING_TYPE: btn3.setChecked(True)
        btn3.toggled.connect(lambda: self.toggle_button(btn3))
        h_layout.addWidget(btn3)
        btn4 = QRadioButton("repeated")
        if btn4.text() == controller_mppi.SAMPLING_TYPE: btn4.setChecked(True)
        btn4.toggled.connect(lambda: self.toggle_button(btn4))
        h_layout.addWidget(btn4)
        btn5 = QRadioButton("interpolated")
        if btn5.text() == controller_mppi.SAMPLING_TYPE: btn5.setChecked(True)
        btn5.toggled.connect(lambda: self.toggle_button(btn5))
        h_layout.addWidget(btn5)
        mppi_constants_layout.addWidget(QLabel("Sampling type:"))
        mppi_constants_layout.addLayout(h_layout)

        ### Put together layout
        self.update_labels()
        self.update_slider_labels()
        layout.addLayout(horizon_options_layout)
        layout.addLayout(rollouts_options_layout)
        layout.addLayout(cost_weight_layout)
        layout.addLayout(mppi_constants_layout)

        self.setLayout(layout)
        self.setWindowFlags(self.windowFlags()
                            | Qt.WindowType.WindowStaysOnTopHint)
        self.setGeometry(0, 0, 400, 50)

        self.show()
        self.setWindowTitle("MPPI Options")

        self.timer = QTimer()
        self.timer.timeout.connect(self.update_labels)
        self.timer.start(100)