Exemple #1
1
 def msg(self):
      #后面四个数字的作用依次是 初始值 最小值 最大值 小数点后位数
     doubleNum,ok1 = QInputDialog.getDouble(self, "标题","计数:", 37.56, -10000, 10000, 2)
      #后面四个数字的作用依次是 初始值 最小值 最大值 步幅
     intNum,ok2 = QInputDialog.getInt(self, "标题","计数:", 37, -10000, 10000, 2)
      #第三个参数可选 有一般显示 (QLineEdit.Normal)、密碼显示( QLineEdit. Password)与不回应文字输入( QLineEdit. NoEcho)
     stringNum,ok3 = QInputDialog.getText(self, "标题","姓名:",QLineEdit.Normal, "王尼玛")
      #1为默认选中选项目,True/False  列表框是否可编辑。
     items = ["Spring", "Summer", "Fall", "Winter"]
     item, ok4 = QInputDialog.getItem(self, "标题","Season:", items, 1, True)
     text, ok5 = QInputDialog.getMultiLineText(self, "标题", "Address:", "John Doe\nFreedom Street")
Exemple #2
0
 def setLogSize(self):
     text = "Maximum log size (0 for infinite):"
     number, ok = QInputDialog.getInt(
         self, "Set log size", text,
         value=self.logWidget.maxlen, min=0)
     if ok:
         self.logWidget.maxlen = number
 def moveSelectedObjects(self):
     moveToIndex, ok = QInputDialog.getInt(self, "Move", "Move to index.", 1, 1, len(self.model().objects))
     if ok:
         moveToIndex -= 1  # From 1-based to 0-based.
         moveToIndex = min([max([0, moveToIndex]), len(self.model().objects)])  # Clamp moveToIndex to a valid object index.
         selectedObjectIndices = self.selectedRows() if self.model().isRowObjects else self.selectedColumns()
         self.model().moveObjects(selectedObjectIndices, moveToIndex)
 def getInteger(self):
     i, okPressed = QInputDialog.getInt(self, "Get integer","Percentage:", 28, 0, 100, 1)
     print(okPressed)
     if okPressed:
         self.amp = i 
         print(i)
         print("amp = ", self.amp)
Exemple #5
0
 def setInterpolate(self):
     text = "Number of points (0 to disable):"
     number, ok = QInputDialog.getInt(
         self, "Set number of data points", text,
         value=self.config.interpolate, min=0)
     if ok:
         self.config.interpolate = number
Exemple #6
0
 def on_pause_action_triggered(self):
     p = self.context_menu_item.model_item.pause if isinstance(self.context_menu_item, MessageItem) else 0
     pause, ok = QInputDialog.getInt(self, self.tr("Enter new pause"),
                                     self.tr("Pause in samples:"), p, 0)
     if ok:
         for msg in self.scene().get_selected_messages():
             msg.pause = pause
Exemple #7
0
    def on_add_message_action_triggered(self):
        num_bits, ok = QInputDialog.getInt(self,
                                           self.tr("How many bits shall the new message have?"),
                                           self.tr("Number of bits:"), 42, 1)

        if ok:
            self.add_empty_message(num_bits)
 def addButtonClicked(self):
     shop = self.shopModel.record(self.list.currentIndex().row())
     query = QSqlQuery("SELECT detail.id as id, CONCAT(detail.article, \": \", detail.name) as name \
         FROM detail WHERE NOT(detail.id IN (SELECT detail_id FROM shop_detail \
             WHERE shop_id={}))".format(shop.value("id")))
     details = {}
     while query.next():
         details[query.value("name")] = query.value("id")
     if not details:
         return QMessageBox.warning(None, "Ошибка добавления",
             "Не удалось добавить новый товар на склад: все возможные товары уже добавлены.")
     choice, ok = QInputDialog.getItem(None, "Товар", "Укажите товар:",
         list(details.keys()), 0, False)
     if not ok: return
     qnt, ok = QInputDialog.getInt(None, "Количество", "Укажите количество товара:",
         1, 1)
     if not ok: return
     detail_id = details[choice]
     shop_id = shop.value("id")
     query = QSqlQuery("INSERT INTO shop_detail (shop_id, detail_id, quantity) \
         VALUES ({}, {}, {})".format(shop_id, detail_id, qnt))
     if not query.isActive():
         print(query.lastError().text())
     self.setShopIndex(self.list.currentIndex().row())
     self.table.selectionModel().clearSelection()
 def on_bTest_clicked(self):
     """
     Private method to test the selected options.
     """
     if self.rText.isChecked():
         if self.rEchoNormal.isChecked():
             echomode = QLineEdit.Normal
         elif self.rEchoNoEcho.isChecked():
             echomode = QLineEdit.NoEcho
         else:
             echomode = QLineEdit.Password
         QInputDialog.getText(
             None,
             self.eCaption.text(),
             self.eLabel.text(),
             echomode,
             self.eTextDefault.text())
     elif self.rInteger.isChecked():
         QInputDialog.getInt(
             None,
             self.eCaption.text(),
             self.eLabel.text(),
             self.sIntDefault.value(),
             self.sIntFrom.value(),
             self.sIntTo.value(),
             self.sIntStep.value())
     elif self.rDouble.isChecked():
         try:
             doubleDefault = float(self.eDoubleDefault.text())
         except ValueError:
             doubleDefault = 0
         try:
             doubleFrom = float(self.eDoubleFrom.text())
         except ValueError:
             doubleFrom = -2147483647
         try:
             doubleTo = float(self.eDoubleTo.text())
         except ValueError:
             doubleTo = 2147483647
         QInputDialog.getDouble(
             None,
             self.eCaption.text(),
             self.eLabel.text(),
             doubleDefault,
             doubleFrom,
             doubleTo,
             self.sDoubleDecimals.value())
Exemple #10
0
    def new_item_edit_options(self, new):
        """Edit the selected item option with custom dialog."""

        if new:
            selected = ItemOptionWidget("", None)
        else:
            selected = self.ui.variant.currentItem()

        # TODO: need a better way to lay this out. it's going to get big and messy fast

        # this is for the qinputdialog stuff. can't set signals on them
        generic = False
        if new:
            # needs to be here or new opts get detected as string (?)
            dialog = ItemEditOptions(self.dialog, selected.option[0], selected.option[1])
            def get_option():
                data = dialog.ui.options.toPlainText()
                return dialog.ui.name.text(), json.loads(data)
        #elif selected.option[0] in ["inventoryIcon", "image", "largeImage"]:
        #    dialog = ImageBrowser(self.dialog, self.assets)
        #    def get_option():
        #        return selected.option[0], dialog.get_key()
        elif type(self.item["parameters"][selected.option[0]]) is str:
            generic = True
            text, ok = QInputDialog.getText(self.dialog, "Edit Text", selected.option[0],
                                            text=self.item["parameters"][selected.option[0]])
            if ok:
                self.item["parameters"][selected.option[0]] = text
        elif type(self.item["parameters"][selected.option[0]]) is int:
            generic = True
            num, ok = QInputDialog.getInt(self.dialog, "Edit Integer", selected.option[0],
                                          self.item["parameters"][selected.option[0]])
            if ok:
                self.item["parameters"][selected.option[0]] = num
        elif type(self.item["parameters"][selected.option[0]]) is float:
            generic = True
            num, ok = QInputDialog.getDouble(self.dialog, "Edit Double", selected.option[0],
                                             self.item["parameters"][selected.option[0]], decimals=2)
            if ok:
                self.item["parameters"][selected.option[0]] = num
        elif type(self.item["parameters"][selected.option[0]]) is bool:
            generic = True
            self.item["parameters"][selected.option[0]] = not self.item["parameters"][selected.option[0]]
        else:
            dialog = ItemEditOptions(self.dialog, selected.option[0], selected.option[1])
            def get_option():
                data = dialog.ui.options.toPlainText()
                return dialog.ui.name.text(), json.loads(data)

        def save():
            new_option = get_option()
            self.item["parameters"][new_option[0]] = new_option[1]

        if not generic:
            dialog.dialog.accepted.connect(save)
            dialog.dialog.exec()

        self.populate_options()
        self.update_item_info(self.item["name"], self.item["parameters"])
Exemple #11
0
 def edit_pause_item(self, index: int):
     message = self.table_model.protocol.messages[index]
     cur_len = message.pause
     new_len, ok = QInputDialog.getInt(self, self.tr("Enter new Pause Length"),
                                       self.tr("Pause Length:"), cur_len, 0)
     if ok:
         message.pause = new_len
         self.refresh_pause_list()
Exemple #12
0
 def AddPoint(self,x,y):
     self.Main.iface.mapCanvas().unsetMapTool(self.AddPointMapTool)
     Point = QgsPointXY(x,y)
     pos = self.player.position()
     if self.player.state() == QMediaPlayer.PlayingState:
         self.player.pause()
     a = self.DBLayer.name()
     last_desc = '///'
     LayerName =str(a)
     last_desc2 = LayerName + ' Point N '
     directory = str(self.DB.split('.')[0])+'_Image/'
     if not os.path.exists(directory):
         os.makedirs(directory)
     fc = int(self.DBLayer.featureCount())
     self.ExtractSingleFrameOnTime(pos,directory+LayerName+'_'+str(fc)+'_.jpg')
     fields = self.DBLayer.fields()
     attributes = []
     lat,lon = Point.y(), Point.x()
     for field in fields:
         a = str(field.name())
         b = str(field.typeName())
         if a == 'id':
             fcnr = fc
             attributes.append(fcnr)  
         elif a == 'Lon(WGS84)':
             attributes.append(str(lon))                       
         elif a == 'Lat(WGS84)':
             attributes.append(str(lat))               
         elif a == 'Image link':
             attributes.append(str(directory+LayerName+'_'+str(fc)+'_.jpg'))                   
         else:                    
             if b == 'String':      
                 (a,ok) = QInputDialog.getText(
                                               self.Main.iface.mainWindow(), 
                                               "Attributes",
                                               a + ' = String',
                                               QLineEdit.Normal)
                 attributes.append(a)               
             elif b == 'Real':                    
                 (a,ok) = QInputDialog.getDouble(
                                                 self.Main.iface.mainWindow(), 
                                                 "Attributes",
                                                 a + ' = Real', decimals = 10)
                 attributes.append(a)
             elif b == 'Integer64':                    
                 (a,ok) = QInputDialog.getInt(
                                              self.Main.iface.mainWindow(), 
                                              "Attributes",
                                              a + ' = Integer')
                 attributes.append(a)                    
     feature = QgsFeature()
     feature.setGeometry(QgsGeometry.fromPoint(Point))
     feature.setAttributes(attributes)
     self.DBLayer.startEditing()
     self.DBLayer.addFeature(feature)
     self.DBLayer.commitChanges()    
     self.DBLayer.triggerRepaint()
Exemple #13
0
 def Crop(self):
     topX, pressed = QInputDialog.getInt(self, "Coordinate", "TopX", 1, 1,
                                         int(self.image.width), 1)
     if pressed:
         topY, pressed = QInputDialog.getInt(self, "Coordinate", "TopY", 1,
                                             1, int(self.image.height), 1)
         if pressed:
             bottomX, pressed = QInputDialog.getInt(self, "Coordinate",
                                                    "BottomX", 1, 1,
                                                    int(self.image.width),
                                                    1)
             if pressed:
                 bottomY, pressed = QInputDialog.getInt(
                     self, "Coordinate", "BottomY", 1, 1,
                     int(self.image.height), 1)
                 if pressed:
                     self.image = self.image.crop(
                         (topX, topY, bottomX, bottomY))
                     self.showImage()
Exemple #14
0
 def changer(self):
     if self.tableWidget.currentRow() != 0:
         if self.tableWidget.currentColumn() == 0:
             pass
         elif self.tableWidget.currentColumn() == 1:
             m = QInputDialog.getText(self, 'Edit', 'Info:')[0]
             if m != '':
                 self.tableWidget.item(self.tableWidget.currentRow(), self.tableWidget.currentColumn()).setText(m)
                 cur = self.con.cursor()
                 result = cur.execute("""UPDATE films
                                         SET title = ?
                                         WHERE ROWID = ?""", (str(m), int(self.tableWidget.currentRow()))).fetchall()
                 self.con.commit()
         elif self.tableWidget.currentColumn() == 2:
             m = QInputDialog.getInt(self, 'Edit', 'Info:', 1, 1, 99999)[0]
             self.tableWidget.item(self.tableWidget.currentRow(), self.tableWidget.currentColumn()).setText(str(m))
             cur = self.con.cursor()
             result = cur.execute("""UPDATE films
                                     SET year = ?
                                     WHERE ROWID = ?""",
                                  (int(m), int(self.tableWidget.currentRow()))).fetchall()
             self.con.commit()
         elif self.tableWidget.currentColumn() == 3:
             cur = self.con.cursor()
             result = cur.execute("Select * from genres").fetchall()
             genres = [i[1] for i in result]
             m = QInputDialog.getItem(self, 'Edit', 'Info:', genres, int(self.tableWidget.item(self.tableWidget.currentRow(), self.tableWidget.currentColumn()).text()) - 1, False)
             self.tableWidget.item(self.tableWidget.currentRow(), self.tableWidget.currentColumn()).setText(str(genres.index(m[0]) + 1))
             cur = self.con.cursor()
             result = cur.execute("""UPDATE films
                                     SET genre = ?
                                     WHERE ROWID = ?""",
                                  (int(genres.index(m[0]) + 1), int(self.tableWidget.currentRow()))).fetchall()
             self.con.commit()
         elif self.tableWidget.currentColumn() == 4:
             m = QInputDialog.getInt(self, 'Edit', 'Info:', int(self.tableWidget.item(self.tableWidget.currentRow(), self.tableWidget.currentColumn()).text()), 1, 999)[0]
             self.tableWidget.item(self.tableWidget.currentRow(), self.tableWidget.currentColumn()).setText(str(m))
             cur = self.con.cursor()
             result = cur.execute("""UPDATE films
                                     SET duration = ?
                                     WHERE ROWID = ?""",
                                  (int(m), int(self.tableWidget.currentRow()))).fetchall()
             self.con.commit()
Exemple #15
0
 def addBorder(self):
     width, ok = QInputDialog.getInt(self, 'Add Border', 'Enter Border Width :', 2, 1)
     if ok:
         painter = QPainter(self.image.pic)
         pen = QPen(Qt.black)
         pen.setWidth(width)
         pen.setJoinStyle(Qt.MiterJoin);
         painter.setPen(pen)
         painter.drawRect(width/2, width/2, self.image.pic.width()-width, self.image.pic.height()-width)
         self.image.showScaled()
Exemple #16
0
 def toggleAutoRefresh(self, enable):
     if enable:
         interval, ok = QInputDialog.getInt(
             self, 'Refresh Interval', 'Enter refresh interval (sec) :', 30,
             5, 300)
         if ok:
             self.timer.setInterval(interval * 1000)
             self.timer.start()
     else:
         self.timer.stop()
Exemple #17
0
 def preprocess(self):
     directory = QFileDialog.getExistingDirectory(self, "Choose your images directory")
     self.image_path.setText(directory)
     if not os.path.exists(directory):
         QMessageBox.information(self, "Bro Studio", "Directory does not exists")
         return None
     should_resize = self.should_resize.isChecked()
     convert_grayscale = self.convert_grayscale.isChecked()
     if should_resize:
         width = QInputDialog.getInt(self, "Resize", "Enter the width")
         height = QInputDialog.getInt(self, "Resize", "Enter the height")
         width = width[0]
         height = height[0]
         print((width, height))
         self.image_thread = PreProcessImageThread(self.signal, directory, convert_grayscale, should_resize,
                                                   size=(width, height))
     else:
         self.image_thread = PreProcessImageThread(self.signal, directory, convert_grayscale, should_resize)
     self.image_thread.start()
Exemple #18
0
    def changeFontSize(self):
        global fontsize

        i, okPressed = QInputDialog.getInt(self, "Set Font Size", "Font Size:",
                                           plt.rcParams['font.size'], 1, 100,
                                           1)
        if okPressed:
            self.fontsize = plt.rcParams['font.size'] = fontsize = i
            self.initCanvas()
            self.m.plot()
Exemple #19
0
 def callback():
     res, ok = QInputDialog.getInt(self,
                                   self.instr_params[ii].gui_name,
                                   self.instr_params[ii].gui_name,
                                   self.instr_params[ii].value)
     if ok:
         self.instr_params[ii].update(res)
         self.param_labels[ii].setText("%s" %
                                       str(self.instr_params[ii]))
         self.send_params()
class window(QMainWindow):
    def __init__(self):
        super(window, self).__init__()
        self.setGeometry(700, 200, 580, 250)
        self.setStyleSheet("background : grey")

        self.b8 = QtWidgets.QPushButton(self)
        self.b8.setGeometry(50, 75, 100, 100)
        self.b8.setText("Set x,y target")
        self.b8.clicked.connect(self.b8_clicked)

        self.b9 = QtWidgets.QPushButton(self)
        self.b9.setGeometry(250, 75, 100, 100)
        self.b9.setText("Set target \n direction and\n distance")
        self.b9.clicked.connect(self.b9_clicked)

        self.b10 = QtWidgets.QPushButton(self)
        self.b10.setGeometry(450, 75, 100, 100)
        self.b10.setText("Set distance")
        self.b10.clicked.connect(self.b10_clicked)

    def b8_clicked(self):
        self.xy = QInputDialog(self)
        self.x, xpressed = self.xy.getInt(self, "Set x target", "", 0, -250,
                                          250, 1)
        self.y, ypressed = self.xy.getInt(self, "Set y target", "", 0, -250,
                                          250, 1)
        gui_pub.publish("xy" + " " + str(self.x) + " " + str(self.y) + " ")

    def b9_clicked(self):
        self.direction_dist = QInputDialog(self)
        self.direction, direction_pressed = self.direction_dist.getInt(
            self, "Set direction", "", 0, -180, 180, 1)
        self.distance, distance_pressed = self.direction_dist.getInt(
            self, "Set distance", "", 0, 0, 250, 1)
        gui_pub.publish("dd" + " " + str(self.direction) + " " +
                        str(self.distance) + " ")

    def b10_clicked(self):
        self.set_loopl = QInputDialog(self)
        self.new_loopl, loopl_pressed = self.set_loopl.getInt(
            self, "Set loopl", "", 0, 0, 250, 1)
        gui_pub.publish("di" + " " + str(self.new_loopl) + " ")
Exemple #21
0
 def __setInterval(self):
     """
     Private slot to change the status check interval.
     """
     interval, ok = QInputDialog.getInt(
         None, self.tr("VCS Status Monitor"),
         self.tr("Enter monitor interval [s]"),
         self.project.getStatusMonitorInterval(), 0, 3600, 1)
     if ok:
         self.project.setStatusMonitorInterval(interval)
Exemple #22
0
def size_window_raise():
    """Вызывается диалоговое окно, предлагающее ввести пользователю размер 
    доски"""

    size, ok = QInputDialog.getInt(QApplication.desktop(), 'Border size',
                                   "Enter a border's size (since 4 to 12):",
                                   value=10, min=4, max=12, step=1)
    if ok:
        return size
    return
Exemple #23
0
    def edit_all_pause_items(self):
        message = self.table_model.protocol.messages[0]
        cur_len = message.pause
        new_len, ok = QInputDialog.getInt(self, self.tr("Enter new Pause Length"),
                                          self.tr("Pause Length:"), cur_len, 0)
        if ok:
            for message in self.table_model.protocol.messages:
                message.pause = new_len

            self.refresh_pause_list()
Exemple #24
0
    def highpass_filter_clicked(self):
        window_size, _ = QInputDialog.getInt(self, "Select window size", "window size", 3)
        img_cpy = self.image.copy()

        channels = img_cpy.image_element.split()
        for channel in channels:
            op.channel_highpass_window(channel, window_size)
        img_cpy.set_pillow_image(Image.merge(img_cpy.image_element.mode, channels))

        self.show_result(img_cpy)
Exemple #25
0
def get_integer():
    """
    QDialog for int needs.
    :return:
    """
    qi = QInputDialog()
    center(qi)
    i, okPressed = qi.getInt(qi, "Get integer", "Price:")
    if okPressed:
        return i
Exemple #26
0
 def search_publisher_by_id(self):
     publisher_id, ok = QInputDialog.getInt(self, "输入出版社 ID", "输入出版社 ID")
     if ok:
         item = self.publisher_manager.search_publisher_with_id(
             publisher_id)
         if item:
             item = [item]
         self.list_publisher(item)
     else:
         QMessageBox.critical(self, "错误", "无法获取输入 ID")
Exemple #27
0
 def edit_zoom(self):
     if self.image.isNull():
         return
     percent, ok = QInputDialog.getInt(None,
                                       "Image Changer - Zoom", "Percent: ",
                                       self.zoomSpinBox.value(), 1, 400)
     if ok:
         self.zoomSpinBox.setValue(percent)
     print("OK: ", ok)
     return
Exemple #28
0
 def c_PEcu_ore(self):
     nPE = len(PuntoExtraccion._registry) - 1
     sPE, ok = QInputDialog.getInt(self, "Gopher Underground",
                                   "Seleccione el Punto de Extraccion: ", 0,
                                   0, nPE, 1)
     if ok:
         string = "Nuevo valor de ley de cobre (%):"
         new, ok = QInputDialog.getDouble(self, "Gopher Underground",
                                          string, 0.5, 0, 100, 2)
         self.PEdict[sPE].cu_ore = new
Exemple #29
0
 def nbShotAction(self):
     '''
     number of snapShot
     '''
     nbShot, ok = QInputDialog.getInt(self, 'Number of SnapShot ',
                                      'Enter the number of snapShot ')
     if ok:
         self.nbShot = int(nbShot)
         if self.nbShot <= 0:
             self.nbShot = 1
Exemple #30
0
 def reset_canvas_action(self):
     if self.canvas_widget.drawing != 0:
         return
     num1, ok1 = QInputDialog.getInt(self, '获取宽度', '输入您的宽度(100~1000)', 600,
                                     100, 1000, 1)
     if ok1:
         num2, ok2 = QInputDialog.getInt(self, '获取高度', '输入您的高度(100~1000)',
                                         600, 100, 1000, 1)
     if ok1 and ok2:
         # 清空画布
         self.list_widget.clear()
         self.item_cnt = 0
         self.canvas_widget.action_stack = []
         self.canvas_widget.temp_id = self.get_id()
         # 更改画布大小
         self.scene = QGraphicsScene(self)
         self.scene.setSceneRect(0, 0, num1, num2)
         self.canvas_widget.setScene(self.scene)
         self.canvas_widget.setFixedSize(num1 + 2, num2 + 2)
Exemple #31
0
    def edit_all_pause_items(self):
        message = self.table_model.protocol.messages[0]
        cur_len = message.pause
        new_len, ok = QInputDialog.getInt(self, self.tr("Enter new Pause Length"),
                                          self.tr("Pause Length:"), cur_len, 0)
        if ok:
            for message in self.table_model.protocol.messages:
                message.pause = new_len

            self.refresh_pause_list()
Exemple #32
0
 def addToDatabase(self):
     num, ok = QInputDialog.getInt(self, "Рейтинг (0-5)", "Введите рейтинг",
                                   0, 0, 5)
     if not ok:
         return None
     l = [("Автор", QLineEdit()), ("Продукт :", QComboBox())]
     l[1][1].addItems(self._myDatabase.products())
     d = myDialog(l, "Добавление")
     if d.exec() == QDialog.Accepted:
         self._myDatabase.add(num, l[0][1].text(), l[1][1].currentText())
Exemple #33
0
    def dialog_wyrd(self):

        newwyrd, okPressed = QInputDialog.getInt(
            self, 'Wyrd change', f"Change wyrd amount to:",
            self.mainwindow.wbid.treasury.wyrd, 0, 99999, 1)
        if okPressed:
            self.mainwindow.wbid.treasury.wyrd = newwyrd

        # relaunch ui to process changes in ui
        self.mainwindow.initUI()
Exemple #34
0
    def dialog_gold(self):

        newgold, okPressed = QInputDialog.getInt(
            self, 'Gold change', f"Change gold amount to:",
            self.mainwindow.wbid.treasury.gold, 0, 99999, 1)
        if okPressed:
            self.mainwindow.wbid.treasury.gold = newgold

        # relaunch ui to process changes in ui
        self.mainwindow.initUI()
Exemple #35
0
 def ctx_menu_teleperiod(self):
     if self.device:
         teleperiod, ok = QInputDialog.getInt(
             self, "Set telemetry period",
             "Input 1 to reset to default\n[Min: 10, Max: 3600]",
             self.device.p['TelePeriod'], 1, 3600)
         if ok:
             if teleperiod != 1 and teleperiod < 10:
                 teleperiod = 10
         self.mqtt.publish(self.device.cmnd_topic("teleperiod"), teleperiod)
Exemple #36
0
 def add_goal(self):
     goal, ok1 = QInputDialog.getText(self, 'Input a new goal', '')
     if ok1:
         amount, ok2 = QInputDialog.getInt(self, 'Input goal amount', '$')
         if ok2:
             try:
                 self.user['goals'][goal] = {'amount': amount, 'paid': 0}
                 self.refresh_goals()
             except:
                 self.error('Error: Could not add goal.')
Exemple #37
0
    def split_queue(self):

        queueNumber, ok = QInputDialog.getText(self, 'Split Queue',
                                               "Enter Queue to be split.")
        if ok and queueNumber:
            queueNumber = queueNumber.lstrip("0")
            machineNumber, ok = QInputDialog.getInt(
                self,
                'Number of Machines',
                'Please enter number of machines (2-9)',
                2,
                2,
                9,
                1,
            )
            if ok and machineNumber:

                lsQueue = []
                lstAll = []
                for file in os.listdir("//qserver/Breeze Artwork Storage"):
                    if file[:len(queueNumber)] == queueNumber:
                        lsQueue.append(file)

                for file in os.listdir(
                        "//qserver/Breeze Artwork Storage/SplitQueues"):
                    if file[2:len(queueNumber) + 2] == queueNumber:
                        os.remove(
                            "//qserver/Breeze Artwork Storage/SplitQueues/" +
                            file)

                for ordr in lsQueue:
                    qty = ordr.split("_")[7]

                    for i in range(int(qty)):
                        lstAll.append(ordr)

                self.startSplit = SplitThread(machineNumber, queueNumber,
                                              lstAll)
                self.startSplit.copied.connect(self.split_progress)
                self.startSplit.splitFinished.connect(self.splitQueueFinish)

                self.progressSplt = ProgressBarSplit(len(lstAll))
                #self.progressSplt.setWindowModality(Qt.WindowModal)
                self.progressSplt.setWindowTitle('Splitting Queues')
                self.progressSplt.setWindowFlags(Qt.WindowStaysOnTopHint)
                self.progressSplt.setWindowIcon(QIcon('icon/scanner.png'))
                self.progressSplt.canceled.connect(self.split_cancel)

                self.startSplit.start()
                self.progressSplt.show()

                self.setEnabled(False)
                bgColor = QPalette()
                bgColor.setColor(self.backgroundRole(), Qt.lightGray)
                self.setPalette(bgColor)
Exemple #38
0
 def pull_split_queue(self):
     mb = QMessageBox()
     ind = QInputDialog()
     
     mb.information(self, "Breeze Software", "Please make sure that you have your Kornit Software open and running.", mb.Ok)
     
     queueNumber, ok = ind.getText(self, "Queue Number", "Please enter queue number.")
     if ok and queueNumber:
         queueNumber = queueNumber.lstrip("0")
         
         firstOrder, ok = ind.getText(self, "Starting Order", "Optional - please enter the beginning order number.")
         if not firstOrder: firstOrder = 1
         
         machineNumber, ok = ind.getInt(self, "Machine Number", "Please enter machine number", 1, 1, 9, 1)
             
         clearHF = mb.question(self, "Hot Folder", "Do you want to clear all the items in the hot folder?", mb.Yes | mb.No, mb.Yes)
     
         if clearHF == mb.Yes:
             dirPath = "C:/HotFolder"
             fileList = os.listdir(dirPath)
             for filename in fileList:
                 item = os.path.join(dirPath,filename)
                 if os.path.isfile(item): 
                     os.remove(item)         
         
         QMessageBox.information(self, 'Pulling Down', 'Your queue should show up in QuickP shortly.')            
         
         front = len(str(machineNumber)) + len(str(queueNumber))+2
         back = len(str(firstOrder)) + front
         
         dir_lst = os.listdir("//qserver/Breeze Artwork Storage/SplitQueues")
         counts = Counter(dir_lst)
                     
         for file in dir_lst:
             if file[:len(str(machineNumber)+"_"+queueNumber)] == str(machineNumber)+"_"+queueNumber and file[front:-(len(file) - back)] >= str(firstOrder):
                 type = file.split("_")
             
                 queue = type[1]
                 order = type[2]
                 skuName = type[3]
                 db = type[4]
                 sizeGarment = type[5]
                 skuType = type[6]
                 printType = type[7]
                 qty = type[8]
                 pos1 = type[9]
                 ext = type[10]
                 
                 fileName = skuType+"_"+printType+"_"+queue+"."+order+"."+skuName+"."+db+"."+sizeGarment+"."+qty+"_"+qty+"_"+pos1+"_"+ext                    
                 shutil.copy(os.path.join("//qserver/Breeze Artwork Storage/SplitQueues", file), os.path.join("c:\HotFolder", fileName))
                 #shutil.copy(os.path.join("//qserver/Breeze Artwork Storage/Test", file), os.path.join("//qserver/BreezeSplitQueues", file))                                        
     elif ok and not queueNumber:
         mb.critical(self, "No Queue Number", "Must enter queue number to continue.")
         if ok == True:
             self.pull_split_queue()
    def detec_prob(self):
        #get the foreground and background file names and info
        #get the file
        file_nameb, ok = QFileDialog.getOpenFileName(
            self, 'Background List Mode File', "",
            'Comma Seperated File (*.csv);;Text File (*.txt)')
        file_namef, ok2 = QFileDialog.getOpenFileName(
            self, 'Foreground List Mode File', "",
            'Comma Seperated File (*.csv);;Text File (*.txt)')
        if ok and ok2:
            num, ok3 = QInputDialog.getInt(self, 'Detection Probability',
                                           'Percentage:', 99, 0, 100)
            if ok3:
                evals = np.linspace(0, 1800, 181)
                detection_probability = DT(file_namef, file_nameb, evals)
                probs = detection_probability.probs
                probs = [i * 100 for i in probs]
                #need to parse through the probabilities and find the first
                #real data point that doesn't represent a statistical anamoly
                #set a lower threshold to start counting at
                threshold = 90  #if the probability drops below this
                s_index = 0
                for i in range(len(probs)):
                    if probs[i] <= threshold:
                        s_index = i
                        break
                probs = probs[s_index::]
                evals = evals[s_index::]
                time_detect = np.interp(num, probs, evals)
                plt.figure(1)
                plt.plot(evals, probs, '*')
                plt.axvline(
                    time_detect,
                    label='Time to {}% detection probability: {:.2f}s'.format(
                        num, time_detect))
                plt.xlabel('Time(s)')
                plt.ylabel('Probability (%)')
                plt.legend()
                # print(probs)
                plt.show()

                #save the raw data out
                fore_sums = detection_probability.f_sums[s_index::]
                back_sums = detection_probability.b_sums[s_index::]
                analysis_times = detection_probability.a_times[s_index::]
                raw_name, ok3 = QFileDialog.getSaveFileName(
                    self, 'Raw Data Save File Name', "",
                    'Comma Seperated File (*.csv);;Text File (*.txt)')
                if ok3:
                    f = open(raw_name, 'w')
                    for i in range(len(fore_sums)):
                        f.write('{},{},{:.4f},{:.4f}\n'.format(
                            fore_sums[i], back_sums[i], analysis_times[i],
                            probs[i]))
                    f.close()
Exemple #40
0
    def see_seam_progress(self):
        # Handle button click progress/steps

        choice = QMessageBox.question(
            self, 'Seam direction',
            "Seam direction: Yes for horizontally, No for vertically, default vertically",
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

        i, okPressed = QInputDialog.getInt(self, "default 50, max 500",
                                           "Number of seams to be removed:",
                                           50, 0, 500, 1)
        # beach pick 50 and vertical
        if okPressed:
            seams_per_iter = i
        else:
            seams_per_iter = 50

        if choice == QMessageBox.Yes:
            direction = 'horizontal'

        else:
            direction = 'vertical'

        name, _ = QFileDialog.getOpenFileName(
            self, 'Open File', options=QFileDialog.DontUseNativeDialog)

        the_image = str(name)

        open_img = cv2.imread(the_image, 1)

        i, user_response = QInputDialog.getInt(self,
                                               " Algorithm type(Default 2) ",
                                               "Which Algorithm type (1-5)", 2,
                                               1, 5, 1)

        # beach pick 50 and vertical
        if okPressed:
            algo_type = i
        else:
            algo_type = 2

        work_work_progress(open_img, direction, seams_per_iter, algo_type)
Exemple #41
0
 def reset_canvas_action(self, resize=True):
     # print(resize)
     if resize:
         self.length = QInputDialog.getInt(self, '请输入', '长度', 800, 200,
                                           1500)[0]
         self.width = QInputDialog.getInt(self, '请输入', '宽度', 800, 200,
                                          900)[0]
     self.list_widget.clearSelection()
     self.list_widget.clear()
     self.canvas_widget.clear_selection()
     self.canvas_widget.item_dict.clear()
     self.canvas_widget.scene().clear()
     self.item_cnt = 0
     self.canvas_widget.status = ''
     self.opened_filename = ''
     self.is_modified = False
     # TODO: 设置长宽
     self.scene.setSceneRect(0, 0, self.length, self.width)
     self.canvas_widget.setFixedSize(self.length, self.width)
     self.setWindowTitle('CG Demo')
Exemple #42
0
 def set_rt(self, idx):
     curr = self.rts[self.rt]
     new, ok = QInputDialog.getInt(self,
                                   "Set ruletimer",
                                   "Set ruletimer{} value.".format(self.rt +
                                                                   1),
                                   value=curr)
     if ok:
         self.sendCommand.emit(
             self.device.cmnd_topic("ruletimer{}".format(self.rt + 1)),
             str(new))
Exemple #43
0
 def invokeGoTo(self):
     """Show GUI dialog, go to line, if user accepted it
     """
     line = self.qutepart.cursorPosition[0]
     gotoLine, accepted = QInputDialog.getInt(self, self.tr("Go To Line..."),
                                              self.tr("Enter the line you want to go to:"),
                                              line, 1, len(self.qutepart.lines), 1)
     if accepted:
         gotoLine -= 1
         self.qutepart.cursorPosition = gotoLine, None
         self.setFocus()
Exemple #44
0
 def edit_window(self):
     global ex2
     ex2 = SecondWindow()
     check_id = QInputDialog.getInt(self, 'id', 'Введите id кофе', 1, 1,
                                    10000, 1)
     con = sqlite3.connect('E:/Python/coffee-database/data/coffee.sqlite')
     cur = con.cursor()
     while not list(
             cur.execute(
                 f'SELECT * FROM type_of_coffee WHERE id = {check_id[0]}')
     ) and check_id[1]:
         QMessageBox.information(self, 'id',
                                 'Кофе с таким id не существует')
         check_id = QInputDialog.getInt(self, 'id', 'Введите id кофе', 1, 1,
                                        10000, 1)
     if check_id[1]:
         con.close()
         ex2.show()
         ex2.edit_coffee(check_id[0])
     con.close()
Exemple #45
0
 def trim(self, direction):
     point = QInputDialog.getInt(None, 'Trim curve', 'Enter wavelength for trimming', self.spectrum.wavelengths[0] if direction == 'before' else self.spectrum.wavelengths[-1], self.spectrum.wavelengths[0], self.spectrum.wavelengths[-1])
     if not point[1]:
         return
     self.undo.save_undo()
     if direction == 'before':
         self.spectrum.cut(start=self.spectrum.wavelength_index(point[0]))
     else:
         self.spectrum.cut(end=self.spectrum.wavelength_index(point[0]))
     self.reset_zoom()
     self.draw()
 def on_btn_repeat_values_clicked(self):
     num_repeats, ok = QInputDialog.getInt(self, self.tr("How many times shall values be repeated?"),
                                                 self.tr("Number of repeats:"), 1, 1)
     if ok:
         self.ui.chkBRemoveDuplicates.setChecked(False)
         min_row, max_row, _, _ = self.ui.tblFuzzingValues.selection_range()
         if min_row == -1:
             start, end = 0, len(self.current_label.fuzz_values)
         else:
             start, end = min_row, max_row + 1
         self.fuzz_table_model.repeat_fuzzing_values(start, end, num_repeats)
Exemple #47
0
 def show_dialog(self, active_name):
     ok, min, step = False, 3, 1
     if active_name in [PolyLine.name(), Polygon.name()]:
         num, ok = QInputDialog.getInt(self,
                                       'Количество точек',
                                       'Введите количество точек',
                                       min=min,
                                       step=step)
     if not ok:
         num = 3
     self.parent.num = num
Exemple #48
0
 def __setInterval(self):
     """
     Private slot to change the status check interval.
     """
     interval, ok = QInputDialog.getInt(
         None,
         self.tr("VCS Status Monitor"),
         self.tr("Enter monitor interval [s]"),
         self.project.getStatusMonitorInterval(),
         0, 3600, 1)
     if ok:
         self.project.setStatusMonitorInterval(interval)
Exemple #49
0
 def blankStock(self):
     printTypes = ("Brother", "Breeze", "Embroidery", "Kornit")
     barcode, ok = QInputDialog.getText(self, "Enter barcode", "Please scan or enter barcode:")
     if ok:
         bc = barcode
         printType, ok = QInputDialog.getItem(self, "Select Print Type", "Print Type", printTypes, 0, True)
         if ok and printType:
             pt = printType
             quantity, ok = QInputDialog.getInt(self, "Quantity", "Please enter quantity:", 1, 0, 25, 1)
             if ok:
                 qty = quantity
                 ImportExportDB.insBlankStock(self, bc, pt, qty)
Exemple #50
0
 def on_deleteAction_triggered(self):
     BlockItem.clear()
     self.skiplist.updateDrawInfo()
     input_ret = QInputDialog.getInt(self, '删除', '请输入ID')
     if input_ret[1]:
         index = input_ret[0]
         self.lockUI()
         self.thr = DeleteThread(self.skiplist.head, index)
         self.thr.opFinished.connect(self.unlockUI)
         self.thr.addBlock.connect(self.addBlock)
         self.thr.opFailed.connect(lambda: QMessageBox.warning(
                 self, '警告', '找不到指定index'))
         self.thr.start()
Exemple #51
0
 def on_insertAction_triggered(self):
     BlockItem.clear()
     self.skiplist.updateDrawInfo()
     input_ret = QInputDialog.getInt(self, '插入', '请输入ID',
             self.skiplist.randomIndex())
     if input_ret[1]:
         index = input_ret[0]
         self.lockUI()
         self.thr = InsertThread(self.skiplist.head, index)
         self.thr.opFinished.connect(self.unlockUI)
         self.thr.opFinished.connect(self.skiplist.updateDrawInfo)
         self.thr.addNode.connect(self.addNode)
         self.thr.addBlock.connect(self.addBlock)
         self.thr.opFailed.connect(lambda: QMessageBox.warning(
                 self, '警告', '不允许重复index'))
         self.thr.start()
 def editButtonClicked(self):
     detail = self.detailModel.record(self.table.currentIndex().row())
     qnt, ok = QInputDialog.getInt(None, "Количество", "Укажите количество товара:",
         detail.value("qnt"), 0)
     if not ok: return
     shop = self.shopModel.record(self.list.currentIndex().row())
     if qnt > 0:
         query = QSqlQuery("UPDATE shop_detail SET quantity={} \
             WHERE shop_id={} AND detail_id={}".format(qnt,
                 shop.value("id"), detail.value("id")))
     else:
         query = QSqlQuery("DELETE FROM shop_detail WHERE \
             shop_id={} AND detail_id={} LIMIT 1".format(
                 shop.value("id"), detail.value("id")))
     if not query.isActive():
         print(query.lastError().text())
     self.setShopIndex(self.list.currentIndex().row())
 def editButtonClicked(self):
     detail = self.detailModel.record(self.orderTable.currentIndex().row())
     qnt, ok = QInputDialog.getInt(None, "Количество", "Укажите количество товара:",
         detail.value("qnt"), 0)
     if not ok: return
     order = self.form.currentRecord()
     if qnt > 0:
         query = QSqlQuery("UPDATE order_detail SET quantity={} \
             WHERE order_id={} AND detail_id={}".format(qnt,
                 order.value("id"), detail.value("id")))
     else:
         query = QSqlQuery("DELETE FROM order_detail WHERE \
             order_id={} AND detail_id={} LIMIT 1".format(
                 order.value("id"), detail.value("id")))
     query.exec_()
     if not query.isActive():
         print(query.lastError().text())
     self.form.update()
Exemple #54
0
    def split_queue(self):

        queueNumber, ok = QInputDialog.getText(self, 'Split Queue', "Enter Queue to be split.")
        if ok and queueNumber:
            queueNumber = queueNumber.lstrip("0")
            machineNumber, ok = QInputDialog.getInt(self, 'Number of Machines', 'Please enter number of machines (2-9)', 2, 2, 9, 1, )
            if ok and machineNumber:
                
                lsQueue = []
                lstAll = []
                for file in os.listdir("//qserver/Breeze Artwork Storage"):
                    if file[:len(queueNumber)] == queueNumber:
                        lsQueue.append(file)
                
                for file in os.listdir("//qserver/Breeze Artwork Storage/SplitQueues"):
                    if file[2:len(queueNumber) +2] == queueNumber:
                        os.remove("//qserver/Breeze Artwork Storage/SplitQueues/" + file)
                
                 
                for ordr in lsQueue:
                    qty = ordr.split("_")[7]
                    
                    for i in range(int(qty)):
                        lstAll.append(ordr)

                self.startSplit = SplitThread(machineNumber, queueNumber, lstAll)   
                self.startSplit.copied.connect(self.split_progress)             
                self.startSplit.splitFinished.connect(self.splitQueueFinish)    
                
                self.progressSplt = ProgressBarSplit(len(lstAll))
                #self.progressSplt.setWindowModality(Qt.WindowModal)
                self.progressSplt.setWindowTitle('Splitting Queues')
                self.progressSplt.setWindowFlags(Qt.WindowStaysOnTopHint)
                self.progressSplt.setWindowIcon(QIcon('icon/scanner.png'))
                self.progressSplt.canceled.connect(self.split_cancel)
                
                self.startSplit.start()
                self.progressSplt.show()
                
                self.setEnabled(False)
                bgColor = QPalette()
                bgColor.setColor(self.backgroundRole(), Qt.lightGray)
                self.setPalette(bgColor)
 def addButtonClicked(self):
     order = self.form.currentRecord()
     query = QSqlQuery("SELECT detail.id as id, CONCAT(detail.article, \": \", detail.name) as name \
         FROM detail WHERE NOT(detail.id IN (SELECT detail_id FROM order_detail \
             WHERE order_id={}))".format(order.value("id")))
     details = {}
     while query.next():
         details[query.value("name")] = query.value("id")
     if not details:
         return QMessageBox.warning(None, "Ошибка добавления",
             "Не удалось добавить новый товар к заказу: все возможные товары уже добавлены.")
     choice, ok = QInputDialog.getItem(None, "Товар", "Укажите товар:",
         list(details.keys()), 0, False)
     if not ok: return
     qnt, ok = QInputDialog.getInt(None, "Количество", "Укажите количество товара:", 1, 1)
     if not ok: return
     detail_id = details[choice]
     order_id = order.value("id")
     query = QSqlQuery("INSERT INTO order_detail (order_id, detail_id, quantity) \
         VALUES ({}, {}, {})".format(order_id, detail_id, qnt))
     if not query.isActive():
         print(query.lastError().text())
     self.form.update()
Exemple #56
0
def edit_variant(parent):
    selected = parent.ui.variant.currentItem()
    current_row = parent.ui.variant.currentRow()
    new_variant = None

    if selected.variant_type == 2:
        # double
        dialog = QInputDialog.getDouble(parent.dialog,
                                        "Edit Value",
                                        selected.variant_name,
                                        selected.variant_value[0],
                                        decimals=2)
        if dialog[1]:
            # didn't realise i was writing lisp
            new_variant = ItemVariant((selected.variant_name, (selected.variant_type, (dialog[0],))))
    elif selected.variant_type == 3:
        # bool
        if selected.variant_value[0] == 1:
            text = "True"
        else:
            text = "False"

        dialog = QInputDialog.getText(parent.dialog,
                                      "Edit Value (True/False)",
                                      selected.variant_name,
                                      QtWidgets.QLineEdit.Normal,
                                      text)
        if dialog[1]:
            if dialog[0] == "True":
                val = (1,)
            else:
                val = (0,)

            new_variant = ItemVariant((selected.variant_name, (selected.variant_type, val)))
    elif selected.variant_type == 4:
        # int (vlq)
        dialog = QInputDialog.getInt(parent.dialog,
                                     "Edit Value",
                                     selected.variant_name,
                                     selected.variant_value)
        if dialog[1]:
            new_variant = ItemVariant((selected.variant_name, (selected.variant_type, dialog[0])))
    elif selected.variant_type == 5:
        # string
        dialog = QInputDialog.getText(parent.dialog,
                                      "Edit Value",
                                      selected.variant_name,
                                      QtWidgets.QLineEdit.Normal,
                                      selected.variant_value)
        if dialog[1]:
            new_variant = ItemVariant((selected.variant_name, (selected.variant_type, dialog[0])))
    elif selected.variant_type == 6:
        # variant list
        variant_edit = VariantEdit(parent.dialog, selected)
        new_variant = ItemVariant((selected.variant_name,
                                   (selected.variant_type, variant_edit.get_variant())))
    elif selected.variant_type == 7:
        # variant dicts
        variant_edit = VariantEdit(parent.dialog, selected)
        new_variant = ItemVariant((selected.variant_name,
                                   (selected.variant_type, variant_edit.get_variant())))

    if new_variant != None:
        parent.ui.variant.setItem(current_row, 0, new_variant)
Exemple #57
0
def get_or_set_config():
    """Get config if exist else Set config if not exist."""
    global config
    log.debug("Vacap Config File: {}.".format(CONFIG_FILENAME))
    days = ["Lunes", "Martes", "Miercoles",
            "Jueves", "Viernes", "Sabado", "Domingo"]
    # if config does not exist or cant be read then try to create it, ask user.
    if not os.path.isfile(CONFIG_FILENAME):
        log.warning("Vacap Config File does not exist; Will try to create it.")
        QMessageBox.information(None, __doc__, "<b>Vamos a Configurar Vacap!.")
        msg = "<b>Hacer un Backup Copia de Seguridad al Iniciar la compu ?."
        _st = QMessageBox.question(
            None, __doc__, msg, QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No) == QMessageBox.Yes
        msg = "<b>Hacer Backup Copia de Seguridad si la compu esta a Bateria ?"
        _bt = QMessageBox.question(
            None, __doc__, msg, QMessageBox.Yes | QMessageBox.No,
            QMessageBox.Yes) == QMessageBox.Yes
        msg = "<b>Que Dia de la Semana Hacer Backup Copia de Seguridad ?."
        _day = str(QInputDialog.getItem(
            None, __doc__, msg, days, 4, False)[0]).lower()
        msg = "<b>A que Hora del Dia hacer Hacer Backup Copia de Seguridad ?."
        _hour = int(QInputDialog.getInt(None, __doc__, msg, 12, 1, 23)[0])
        msg = "<b>Donde Guardar el Backup Copia de Seguridad ?."
        QMessageBox.information(None, __doc__, msg)
        _trg = QFileDialog.getExistingDirectory(None, __doc__, gettempdir())
        msg = "<b>Agregar 1 Carpeta para hacer Backup Copia de Seguridad ?."
        _backup_from = []
        while QMessageBox.question(
            None, __doc__, msg, QMessageBox.Yes | QMessageBox.No,
                QMessageBox.Yes) == QMessageBox.Yes:
            _backup_from.append(str(QFileDialog.getExistingDirectory(
                None, __doc__, os.path.expanduser("~"))))
        configura = {
            "MAKE_BACKUP_FROM": _backup_from,
            "SAVE_BACKUP_TO": _trg,
            "MAKE_BACKUP_ON_STARTUP": _st,
            "MAKE_BACKUP_WHEN_RUNNING_ON_BATTERY": _bt,
            "MAKE_BACKUP_ON_WEEK_DAY": _day,
            "MAKE_BACKUP_AT_THIS_HOUR": _hour,
        }
        config = dumps(configura, ensure_ascii=False, indent=4, sort_keys=True)
        log.debug("Configuration: {}.".format(config))
        confirm = QInputDialog.getMultiLineText(
            None, __doc__, "<b>Resumen Final de la Configuracion:", config)[1]
        if confirm:
            with open(CONFIG_FILENAME, "w", encoding="utf-8") as _config:
                _config.write(config)
            try:
                log.info("Making Config {} Hidden".format(CONFIG_FILENAME))
                ctypes.windll.kernel32.SetFileAttributesW(CONFIG_FILENAME,
                                                          0x02)  # hidden file
                log.info("Making Config {} ReadOnly.".format(CONFIG_FILENAME))
                os.chmod(CONFIG_FILENAME, S_IREAD)  # make read-only
            except Exception as reason:
                log.critical(reason)
        else:
            return get_or_set_config()
    else:
        log.debug("Reading/Parsing Config File: {}.".format(CONFIG_FILENAME))
        with open(CONFIG_FILENAME, "r", encoding="utf-8") as _config:
            config = loads(_config.read())
    return config
Exemple #58
0
 def penWidth(self):
     newWidth, ok = QInputDialog.getInt(self, "Scribble",
             "Select pen width:", self.scribbleArea.penWidth(), 1, 50, 1)
     if ok:
         self.scribbleArea.setPenWidth(newWidth)
Exemple #59
0
    def new_item_edit_options(self, new=False, raw=False):
        """Edit the selected item option with custom dialog."""

        if new:
            selected = ItemOptionWidget("", None)
        else:
            selected = self.ui.variant.currentItem()

        dialog = None
        name, value = selected.option

        # TODO: drawable images
        # TODO: status effects
        # TODO: color editing

        if new or raw:
            dialog = ItemEditOptions(self.dialog, name, value)

            def save():
                name, value = dialog.get_option()
                self.item["parameters"][name] = value

            dialog.dialog.accepted.connect(save)
            dialog.dialog.exec()
        elif name in ["inventoryIcon", "image", "largeImage"] and type(value) is str:
            dialog = ImageBrowser(self.dialog, self.assets, False)

            def save():
                value = dialog.get_key()
                self.item["parameters"][name] = value

            dialog.dialog.accepted.connect(save)
            dialog.dialog.exec()
        elif type(value) is str:
            text, ok = QInputDialog.getText(self.dialog, "Edit Text", name, text=value)
            if ok:
                value = text
                self.item["parameters"][name] = value
        elif type(value) is int:
            num, ok = QInputDialog.getInt(self.dialog, "Edit Integer", name, value)
            if ok:
                value = num
                self.item["parameters"][name] = value
        elif type(value) is float:
            num, ok = QInputDialog.getDouble(self.dialog, "Edit Double", name, value, decimals=2)
            if ok:
                value = num
                self.item["parameters"][name] = value
        elif type(value) is bool:
            value = not value
            self.item["parameters"][name] = value
        else:
            dialog = ItemEditOptions(self.dialog, name, value)

            def save():
                name, value = dialog.get_option()
                self.item["parameters"][name] = value

            dialog.dialog.accepted.connect(save)
            dialog.dialog.exec()

        self.update()
 def on_add_message_action_triggered(self):
     row = self.rowAt(self.context_menu_pos.y())
     num_bits, ok = QInputDialog.getInt(self, self.tr("How many bits shall the new message have?"),
                                        self.tr("Number of bits:"), 42, 1)
     if ok:
         self.model().add_empty_row_behind(row, num_bits)