class QSeadTargetInfoView(QGroupBox):
    """
    UI Component to display info about a sead target
    """
    def __init__(self, sead_target_infos: SEADTargetInfo):
        if sead_target_infos is None:
            sead_target_infos = SEADTargetInfo()
        super(QSeadTargetInfoView,
              self).__init__("Target : " + sead_target_infos.name)
        self.sead_target_infos = sead_target_infos
        self.radar_list = QListView()
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout(self)
        layout.setSpacing(0)
        layout.addWidget(self.radar_list)
        self.setLayout(layout)

    def setTarget(self, target: SEADTargetInfo):
        self.setTitle(target.name)
        self.sead_target_infos = target
        radar_list_model = QStandardItemModel()
        self.radar_list.setSelectionMode(QAbstractItemView.NoSelection)
        for r in self.sead_target_infos.radars:
            radar_list_model.appendRow(QStandardItem(r.type))
        self.radar_list.setModel(radar_list_model)
예제 #2
0
class VisualController(Controller):
    def __init__(self):
        super().__init__()
        self.results = QStringListModel(["Worker Results:"])
        self.listview = QListView()
        self.listview.setModel(self.results)

    def start(self):
        super().start()
        self.listview.show()

    @Slot(int)
    def on_worker_result(self, result: int):
        super().on_worker_result(result)
        row_count = self.results.rowCount()
        assert self.results.insertRows(row_count, 1)
        new_row_idx = self.results.index(row_count, 0)
        self.results.setData(new_row_idx, str(result))
        self._resize_to_fit_contents()

    def _resize_to_fit_contents(self):
        QApplication.processEvents()
        view_geo = self.listview.geometry()
        view_geo.setHeight(
            max(view_geo.height(),
                self.listview.contentsSize().height()))
        self.listview.setGeometry(view_geo)
예제 #3
0
    def __init__(self) -> None:
        QWidget.__init__(self)

        # self.index stores the index of the latest item which is clicked
        self.index = None

        self.model = QStandardItemModel()

        file_view = QListView()
        file_view.setModel(self.model)
        file_view.setEditTriggers(QAbstractItemView.NoEditTriggers)
        file_view.clicked.connect(self.onClicked)
        file_view.doubleClicked.connect(self.onDoubleClicked)

        open_file_button = QPushButton('Open')
        open_file_button.clicked.connect(self.onOpenFile)

        preview_file_button = QPushButton('Preview')
        preview_file_button.clicked.connect(self.onPreviewFile)

        layout = QGridLayout()
        layout.addWidget(file_view, 0, 0, 1, 2)
        layout.addWidget(open_file_button, 1, 0, 1, 1)
        layout.addWidget(preview_file_button, 1, 1, 1, 1)
        layout.setMargin(0)
        self.setLayout(layout)
class QStrikeTargetInfoView(QGroupBox):
    """
    UI Component to display info about a strike target
    """

    def __init__(self, strike_target_infos: StrikeTargetInfo):

        if strike_target_infos is None:
            strike_target_infos = StrikeTargetInfo()

        super(QStrikeTargetInfoView, self).__init__(
            "Target : " + strike_target_infos.name
        )

        self.strike_target_infos = strike_target_infos

        self.listView = QListView()

        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout(self)
        layout.setSpacing(0)
        layout.addWidget(self.listView)
        self.setLayout(layout)

    def setTarget(self, target):

        self.setTitle(target.name)
        self.strike_target_infos = target
        model = QStandardItemModel()
        self.listView.setSelectionMode(QAbstractItemView.NoSelection)

        if len(self.strike_target_infos.units) > 0:
            dic = {}
            for u in self.strike_target_infos.units:
                if u.type in dic.keys():
                    dic[u.type] = dic[u.type] + 1
                else:
                    dic[u.type] = 1
            for k, v in dic.items():
                model.appendRow(QStandardItem(k + " x " + str(v)))
                print(k + " x " + str(v))
        else:
            dic = {}
            for b in self.strike_target_infos.buildings:
                id = b.dcs_identifier
                if b.is_dead:
                    id = id + "[Destroyed]"
                if id in dic.keys():
                    dic[id] = dic[id] + 1
                else:
                    dic[id] = 1
            for k, v in dic.items():
                model.appendRow(QStandardItem(k + " x " + str(v)))
                print(k + " x " + str(v))

        self.listView.setModel(model)
예제 #5
0
class MyWidget(QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        self.content_layout = QHBoxLayout()
        self.podcasts_list = QListView()
        self.item_list = QListView()
        self.item_list.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.podcasts_list.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.duration = 0
        self.playtime_label = QLabel()
        self.duration_label = QLabel()
        self.playtime_label.setTextFormat(QtCore.Qt.PlainText)
        self.duration_label.setTextFormat(QtCore.Qt.PlainText)
        self.playtime_label.setText("00:00:00")
        self.playtime_label.setFixedHeight(20)
        self.duration_label.setText("00:00:00")
        self.duration_label.setFixedHeight(20)

        self.progress_bar = QSlider(QtCore.Qt.Horizontal)

        self.content_layout.addWidget(self.podcasts_list)
        self.content_layout.setStretch(0, 2)
        self.content_layout.addWidget(self.item_list)
        self.content_layout.setStretch(1, 8)
        self.download_button = QPushButton("&Download")
        self.play_botton = QPushButton("&Play")

        self.status_layout = QHBoxLayout()
        self.status_layout.addWidget(self.playtime_label)
        self.status_layout.addWidget(self.progress_bar)
        self.status_layout.addWidget(self.duration_label)
        # self.status_layout.addWidget(self.play_botton)
        # self.status_layout.addWidget(self.download_button)

        self.layout = QVBoxLayout()
        self.layout.addLayout(self.content_layout)
        self.layout.addLayout(self.status_layout)

        self.setLayout(self.layout)

    def update_podcasts_list(self, names):
        model = QStringListModel(names)
        self.podcasts_list.setModel(model)

    def update_items_list(self, names):
        model = QStringListModel(names)
        self.item_list.setModel(model)

    def set_progress(self, progress):
        self.progress_bar.setValue(progress)
        self.playtime_label.setText(time_string(progress))

    def set_duration(self, duration):
        self.duration = duration
        self.progress_bar.setRange(0, duration)
        self.duration_label.setText(time_string(duration))
예제 #6
0
    def getView(self):
        """Get a new QListView suitable for displaying the toolbox."""
        v = QListView()
        v.setModel(self)

        v.setSelectionMode(v.SingleSelection)
        v.setDragEnabled(True)
        v.setDragDropMode(v.DragOnly)

        return v
예제 #7
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.workers = WorkerManager()

        self.workers.status.connect(self.statusBar().showMessage)

        layout = QVBoxLayout()

        self.progress = QListView()
        self.progress.setModel(self.workers)
        delegate = ProgressBarDelegate()
        self.progress.setItemDelegate(delegate)

        layout.addWidget(self.progress)

        self.text = QPlainTextEdit()
        self.text.setReadOnly(True)

        start = QPushButton("Start a worker")
        start.pressed.connect(self.start_worker)

        clear = QPushButton("Clear")
        clear.pressed.connect(self.workers.cleanup)

        layout.addWidget(self.text)
        layout.addWidget(start)
        layout.addWidget(clear)

        w = QWidget()
        w.setLayout(layout)

        self.setCentralWidget(w)

        self.show()

    # tag::startWorker[]
    def start_worker(self):
        x = random.randint(0, 1000)
        y = random.randint(0, 1000)

        w = Worker(x, y)
        w.signals.result.connect(self.display_result)
        w.signals.error.connect(self.display_result)

        self.workers.enqueue(w)

    # end::startWorker[]

    def display_result(self, job_id, data):
        self.text.appendPlainText("WORKER %s: %s" % (job_id, data))
예제 #8
0
class FilePicker(QGroupBox):
    def __init__(self, files):
        super().__init__("File Picker")

        self.setLayout(QVBoxLayout())

        self.file_sequence = FileSequence([])

        self._initialize_file_list()

        self.file_sequence = FileSequence(files)
        self._update_file_picker_list([str(file) for file in files])

    def log_file_sequence_status(self):
        logging.debug(f"Current file sequence: {self.file_sequence}")

    def clear_file_list(self):
        self.file_sequence = FileSequence([])
        self.file_list.model().clear()
        self.log_file_sequence_status()

    def _initialize_file_list(self):
        self.file_list = QListView()
        self.file_list.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.layout().addWidget(self.file_list)

        self.file_list.setModel(QStandardItemModel())

        select_files = QPushButton("Select Files")
        select_files.clicked.connect(self._select_files_listener)
        self.layout().addWidget(select_files)

    def _update_file_picker_list(self, file_names):
        model = self.file_list.model()

        # Update File Picker list from files[]
        model.clear()
        for f in range(self.file_sequence.rowCount()):
            item = QStandardItem()
            item.setText(file_names[f])
            model.appendRow(item)

        self.log_file_sequence_status()

    def _select_files_listener(self):
        """Handles selection of files to rename"""

        files = QFileDialog.getOpenFileNames(self, "Select Files", ".")
        self.file_sequence = FileSequence(files[0])

        self._update_file_picker_list(files[0])
class ManagePluginsDialog(QDialog):
    item_removed = Signal(str)
    item_updated = Signal(str)

    def __init__(self, parent):
        """Initialize class"""
        super().__init__(parent)
        self.setWindowTitle('Manage plugins')
        QVBoxLayout(self)
        self._list_view = QListView(self)
        self._model = _ManagePluginsModel(self)
        self._list_view.setModel(self._model)
        self._button_box = QDialogButtonBox(self)
        self._button_box.setStandardButtons(QDialogButtonBox.Close)
        self.layout().addWidget(self._list_view)
        self.layout().addWidget(self._button_box)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setMinimumWidth(400)
        self._button_box.button(QDialogButtonBox.Close).clicked.connect(
            self.close)

    def populate_list(self, names):
        for name, can_update in names:
            item = QStandardItem(name)
            self._model.appendRow(item)
            widget = self._create_plugin_widget(name, can_update)
            index = self._model.indexFromItem(item)
            self._list_view.setIndexWidget(index, widget)

    def _create_plugin_widget(self, plugin_name, can_update):
        widget = ToolBarWidget(plugin_name, self)
        widget.tool_bar.addAction(
            "Remove",
            lambda _=False, n=plugin_name: self._emit_item_removed(n))
        update = widget.tool_bar.addAction(
            "Update",
            lambda _=False, n=plugin_name: self._emit_item_updated(n))
        update.setEnabled(can_update)
        update.triggered.connect(lambda _=False: update.setEnabled(False))
        return widget

    def _emit_item_removed(self, plugin_name):
        for row in range(self._model.rowCount()):
            if self._model.index(row, 0).data(Qt.DisplayRole) == plugin_name:
                self._model.removeRow(row)
                break
        self.item_removed.emit(plugin_name)

    def _emit_item_updated(self, plugin_name):
        self.item_updated.emit(plugin_name)
예제 #10
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.job = JobManager()

        self.job.status.connect(self.statusBar().showMessage)
        self.job.result.connect(self.display_result)

        layout = QVBoxLayout()

        self.progress = QListView()
        self.progress.setModel(self.job)
        delegate = ProgressBarDelegate()
        self.progress.setItemDelegate(delegate)

        layout.addWidget(self.progress)

        self.text = QPlainTextEdit()
        self.text.setReadOnly(True)

        button = QPushButton("Run a command")
        button.pressed.connect(self.run_command)

        clear = QPushButton("Clear")
        clear.pressed.connect(self.job.cleanup)

        layout.addWidget(self.text)
        layout.addWidget(button)
        layout.addWidget(clear)

        w = QWidget()
        w.setLayout(layout)

        self.setCentralWidget(w)

        self.show()

    # tag::startJob[]
    def run_command(self):
        self.job.execute(
            "python",
            ['dummy_script.py'],
            parsers=parsers(progress=simple_percent_parser, data=extract_vars),
        )

    # end::startJob[]

    def display_result(self, job_id, data):
        self.text.appendPlainText("WORKER %s: %s" % (job_id, data))
예제 #11
0
    def __create_vertical_section(self, group_name):
        # Setup layout
        groupbox = QGroupBox(group_name)
        groupbox.setObjectName(group_name)
        vertical_layout = QVBoxLayout()
        groupbox.setLayout(vertical_layout)

        '''
        Add widgets
        '''
        # Add file selection/loading widgets
        file_select_organizer = QHBoxLayout()
        text_input = QLineEdit() # Does this need a name yet?
        file_select_button = QPushButton("...")
        file_select_organizer.addWidget(text_input)
        file_select_organizer.addWidget(file_select_button)
        # Add the section we just made to layout
        vertical_layout.addLayout(file_select_organizer)

        # add listview for excel pages
        excel_label = QLabel("Excel Workbook Pages")
        excel_sheets = QListView()
        excel_sheets.setEditTriggers(QAbstractItemView.NoEditTriggers)
        excel_label_model = QStandardItemModel()
        excel_sheets.setModel(excel_label_model)

        vertical_layout.addWidget(excel_label)
        vertical_layout.addWidget(excel_sheets)


        # add listview for column headers
        variable_label = QLabel("Merge on column:")
        variables = QListView()
        variables.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.columns[group_name] = variables
        variables_model = QStandardItemModel()
        variables.setModel(variables_model)
        vertical_layout.addWidget(variable_label)
        vertical_layout.addWidget(variables)

        '''
        Connect Functions
        '''
        # Connect File dialog to file selection
        file_select_button.clicked.connect(lambda: self.openFileNameDialog(text_input, excel_label_model, group_name))
        # Connect listview to populate listview for column headers
        excel_sheets.clicked.connect(lambda x: self.populateColumns(x, excel_label_model, variables_model, group_name))

        return groupbox
예제 #12
0
    def init_ui(self):
        vbox = QVBoxLayout()
        self.setLayout(vbox)

        lv = QListView()
        lv.clicked.connect(self.on_clicked)
        vbox.addWidget(lv)

        model = QStandardItemModel(lv)
        lv.setModel(model)

        for food in self.foods:
            item = QStandardItem(food)
            item.setCheckable(True)
            model.appendRow(item)
예제 #13
0
    def initUI(self):
        self.setWindowTitle("list view")
        self.setGeometry(500,500,300,300)

        listview = QListView()
        slm = QStringListModel()
        self.qList = ['item1','item2','item3','item4']
        slm.setStringList(self.qList)
        listview.setModel(slm)
        listview.clicked.connect(self.clicked)
         

        layout = QVBoxLayout()
        layout.addWidget(listview)
        self.setLayout(layout)

        self.show()
예제 #14
0
class ChoiceFilterWidget(AbstractFilterWidget):
    def __init__(self, field: str, parent=None):
        super().__init__(parent)

        self.field = field
        vlayout = QVBoxLayout()
        vlayout.setContentsMargins(0, 0, 0, 0)
        self.view = QListView()
        self.model = QStringListModel()
        self.view.setModel(self.model)
        vlayout.addWidget(self.view)
        self.setLayout(vlayout)

    def setup(self, conn: sqlite3.Connection):
        self.model.setStringList(sql.get_field_unique_values(conn, self.field))

    def get_filters(self):
        name = self.field
        return ""
예제 #15
0
    class rename_one(QWidget):

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


            self.mydelegate = MyDelegate()

            self.listview = QListView()
            self.mymodel = QStringListModel()
            self.listview.setModel(self.mymodel)
            # 设置我们自己的delegate
            self.listview.setItemDelegate(self.mydelegate)
            self.battle_allies=r'battle_allies'
            self.battle_allies_list=[]
            for i in range (1,11):
                self.battle_allies_list.append(self.battle_allies+'%s.xml'%str(i))
            self.mymodel.setStringList(self.battle_allies_list)
            print(self.battle_allies_list)
            print(self.mymodel.index(2,0).data())
예제 #16
0
class TransformationLibrary(QGroupBox):
    def __init__(self, transformation_confirmation):
        super().__init__("Transformation Library")

        self.transformation_configuration = transformation_confirmation

        self.setLayout(QVBoxLayout())

        self._initialize_library()

    def _initialize_library(self):
        self.transformation_list = QListView()
        self.transformation_list.setEditTriggers(
            QAbstractItemView.NoEditTriggers)
        self.layout().addWidget(self.transformation_list)

        self.transformation_list.setModel(QStandardItemModel())

        self.transformation_list.clicked.connect(self.configure_transformation)

        # Populate transformations list
        for transformation in TRANSFORMATIONS:
            transformation_name = transformation.schema["metadata"]["name"]
            transformation_description = transformation.schema["metadata"][
                "description"]

            transformation_element = QStandardItem()
            transformation_element.setText(transformation_name)
            transformation_element.setToolTip(transformation_description)

            self.transformation_list.model().appendRow(transformation_element)

    def configure_transformation(self, x):
        """Resolve selected transformation and pass it to transformation_configuration to display config"""

        model = self.transformation_list.model()
        selected_transformation = TRANSFORMATIONS_BY_NAME[model.data(x)]
        logging.debug(f"Selected transformation: {selected_transformation}")

        self.transformation_configuration.swap_configuration(
            selected_transformation)
예제 #17
0
def using_model():
    app = QApplication()
    numbers = ['One', 'Two', 'Three', 'Four', 'Five']

    model = QStringListModel()
    model.setStringList(numbers)

    list = QListView()
    list.setModel(model)

    firstTableView = QTableView()
    secondTableView = QTableView()

    firstTableView.setModel(model)
    secondTableView.setModel(model)
    secondTableView.setSelectionModel(firstTableView.selectionModel())

    list.show()
    firstTableView.show()
    secondTableView.show()
    app.exec_()
예제 #18
0
class Crossing(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Instance modelu
        self.model = CrossingModel()

        # Instance síťového připojení
        self.network = CrossingNetwork(self.model)

        # Výroba ovládacích prvků
        self.connectButton = QPushButton(self, text="Start")
        self.connectButton.clicked.connect(self.network.socketConnect)

        self.disconnectButton = QPushButton(self, text="Stop")
        self.disconnectButton.clicked.connect(self.network.socketDisconnect)

        # Zobrazení dat a propojení s modelem
        self.listView = QListView(self)
        self.listView.setModel(self.model)

        # Zobrazení stavu
        self.stateLabel = QLabel(self, text="Inactive")
        self.network.stateChanged.connect(self.stateChanged)

        # Rozložení ovládacích prvků
        self.layout = QVBoxLayout(self)
        self.layout.addWidget(self.connectButton)
        self.layout.addWidget(self.disconnectButton)
        self.layout.addWidget(self.listView)
        self.layout.addWidget(self.stateLabel)

        # Zobrazení
        self.setLayout(self.layout)
        self.show()

    # Aktualizátor stavového labelu
    @Slot(str)
    def stateChanged(self, state):
        self.stateLabel.setText(state)
예제 #19
0
    def _load(self):
        if self.loaded:
            return

        self.service = locator.get_scoped("DialogueService")
        module_service = locator.get_scoped("ModuleService")
        characters_model = module_service.get_module(
            "Characters").entries_model

        layout = QHBoxLayout(self)
        characters_list = QListView()
        characters_list.setModel(characters_model)
        characters_list.setSizePolicy(
            QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding))
        characters_list.selectionModel().currentRowChanged.connect(
            self._update_selection)
        self.list = characters_list

        scroll_area = QScrollArea()
        form_container = QWidget()
        form = QFormLayout()
        self.editors = []
        for dialogue in self.service.dialogues:
            label = QLabel(dialogue.name)
            editor = QLineEdit()
            editor.editingFinished.connect(
                lambda e=editor, d=dialogue: self._on_editor_change(e, d))
            self.editors.append(editor)
            form.addRow(label, editor)
        form_container.setLayout(form)
        scroll_area.setWidgetResizable(True)
        scroll_area.setWidget(form_container)

        layout.addWidget(characters_list)
        layout.addWidget(scroll_area)
        self.setLayout(layout)

        self.service.load()
        self.loaded = True
예제 #20
0
def model_view():
    app = QApplication()
    splitter = QSplitter()

    model = QFileSystemModel()
    model.setRootPath(QDir.currentPath())
    parentIndex = model.index(QDir.currentPath())

    tree = QTreeView(splitter)
    tree.setModel(model)
    tree.setRootIndex(parentIndex)

    list = QListView(splitter)
    list.setModel(model)
    list.setRootIndex(parentIndex)

    table = QTableView(splitter)
    table.setModel(model)
    table.setRootIndex(parentIndex)

    splitter.setWindowTitle("Two views onto the same file system model")
    splitter.show()
    app.exec_()
예제 #21
0
    def init_ui(self):
        self.button = PButton("Generate...")
        #settings = get_conan_config() # should be a tree?
        self.recipeBox = RecipeBox("HPS")
        self.settings = SettingsBox("Settings")
        self.layout.addWidget(self.recipeBox)
        self.options = OptionsBox("Options")
        self.deps = DepsBox("Dependencies")
        self.recipeBox.layout.addWidget(self.settings)
        self.recipeBox.layout.addWidget(self.deps)
        self.recipeBox.layout.addWidget(self.options)

        for k, v in self.settings_dict.items():
            self.settings.layout.addWidget(QLabel("%s : %s" % (k, v)))

        option_list_view = QListView()
        self.options_model = QStandardItemModel(option_list_view)
        for item in self.options_list:
            #TODO: Clean this up and get it out of ui init before it gets out of hand
            opt = item.split(":")
            v = opt.pop().strip()
            k = ":".join(opt)
            self.individual_option = QStandardItem(k)
            self.individual_option.setCheckable(True)
            self.individual_option.setEditable(False)
            if v == "True":
                self.individual_option.setCheckState(Qt.Checked)
            self.options_model.appendRow(self.individual_option)
        option_list_view.setModel(self.options_model)
        option_list_view.setAlternatingRowColors(True)
        self.options.layout.addWidget(option_list_view)

        self.layout.addWidget(self.button)
        self.setWindowTitle("PynCon")
        self.button.clicked.connect(self.button_click)
        self.show()
예제 #22
0
class QSettingsWindow(QDialog):

    def __init__(self, game: Game):
        super(QSettingsWindow, self).__init__()

        self.game = game

        self.setModal(True)
        self.setWindowTitle("Settings")
        self.setWindowIcon(CONST.ICONS["Settings"])
        self.setMinimumSize(600, 250)

        self.initUi()

    def initUi(self):
        self.layout = QGridLayout()

        self.categoryList = QListView()
        self.right_layout = QStackedLayout()

        self.categoryList.setMaximumWidth(175)

        self.categoryModel = QStandardItemModel(self.categoryList)

        difficulty = QStandardItem("Difficulty")
        difficulty.setIcon(CONST.ICONS["Missile"])
        difficulty.setEditable(False)
        difficulty.setSelectable(True)

        generator = QStandardItem("Mission Generator")
        generator.setIcon(CONST.ICONS["Generator"])
        generator.setEditable(False)
        generator.setSelectable(True)

        cheat = QStandardItem("Cheat Menu")
        cheat.setIcon(CONST.ICONS["Cheat"])
        cheat.setEditable(False)
        cheat.setSelectable(True)

        self.categoryList.setIconSize(QSize(32, 32))
        self.categoryModel.appendRow(difficulty)
        self.categoryModel.appendRow(generator)
        self.categoryModel.appendRow(cheat)

        self.categoryList.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.categoryList.setModel(self.categoryModel)
        self.categoryList.selectionModel().setCurrentIndex(self.categoryList.indexAt(QPoint(1,1)), QItemSelectionModel.Select)
        self.categoryList.selectionModel().selectionChanged.connect(self.onSelectionChanged)

        self.initDifficultyLayout()
        self.initGeneratorLayout()
        self.initCheatLayout()

        self.right_layout.addWidget(self.difficultyPage)
        self.right_layout.addWidget(self.generatorPage)
        self.right_layout.addWidget(self.cheatPage)

        self.layout.addWidget(self.categoryList, 0, 0, 1, 1)
        self.layout.addLayout(self.right_layout, 0, 1, 5, 1)

        self.setLayout(self.layout)

    def init(self):
        pass

    def initDifficultyLayout(self):

        self.difficultyPage = QWidget()
        self.difficultyLayout = QGridLayout()
        self.difficultyLayout.setAlignment(Qt.AlignTop)
        self.difficultyPage.setLayout(self.difficultyLayout)

        self.playerCoalitionSkill = QComboBox()
        self.enemyCoalitionSkill = QComboBox()
        self.enemyAASkill = QComboBox()
        for skill in CONST.SKILL_OPTIONS:
            self.playerCoalitionSkill.addItem(skill)
            self.enemyCoalitionSkill.addItem(skill)
            self.enemyAASkill.addItem(skill)

        self.playerCoalitionSkill.setCurrentIndex(CONST.SKILL_OPTIONS.index(self.game.settings.player_skill))
        self.enemyCoalitionSkill.setCurrentIndex(CONST.SKILL_OPTIONS.index(self.game.settings.enemy_skill))
        self.enemyAASkill.setCurrentIndex(CONST.SKILL_OPTIONS.index(self.game.settings.enemy_vehicle_skill))

        self.playerCoalitionSkill.currentIndexChanged.connect(self.applySettings)
        self.enemyCoalitionSkill.currentIndexChanged.connect(self.applySettings)
        self.enemyAASkill.currentIndexChanged.connect(self.applySettings)

        self.difficultyLayout.addWidget(QLabel("Player coalition skill"), 0, 0)
        self.difficultyLayout.addWidget(self.playerCoalitionSkill, 0, 1, Qt.AlignRight)
        self.difficultyLayout.addWidget(QLabel("Enemy skill"), 1, 0)
        self.difficultyLayout.addWidget(self.enemyCoalitionSkill, 1, 1, Qt.AlignRight)
        self.difficultyLayout.addWidget(QLabel("Enemy AA and vehicles skill"), 2, 0)
        self.difficultyLayout.addWidget(self.enemyAASkill, 2, 1, Qt.AlignRight)

        self.difficultyLabel = QComboBox()
        [self.difficultyLabel.addItem(t) for t in CONST.LABELS_OPTIONS]
        self.difficultyLabel.setCurrentIndex(CONST.LABELS_OPTIONS.index(self.game.settings.labels))
        self.difficultyLabel.currentIndexChanged.connect(self.applySettings)

        self.difficultyLayout.addWidget(QLabel("In Game Labels"), 3, 0)
        self.difficultyLayout.addWidget(self.difficultyLabel, 3, 1, Qt.AlignRight)

        self.noNightMission = QCheckBox()
        self.noNightMission.setChecked(self.game.settings.night_disabled)
        self.noNightMission.toggled.connect(self.applySettings)
        self.difficultyLayout.addWidget(QLabel("No night missions"), 4, 0)
        self.difficultyLayout.addWidget(self.noNightMission, 4, 1, Qt.AlignRight)

        self.mapVisibiitySelection = QComboBox()
        self.mapVisibiitySelection.addItem("All", ForcedOptions.Views.All)
        if self.game.settings.map_coalition_visibility == ForcedOptions.Views.All:
            self.mapVisibiitySelection.setCurrentIndex(0)
        self.mapVisibiitySelection.addItem("Fog of War", ForcedOptions.Views.Allies)
        if self.game.settings.map_coalition_visibility == ForcedOptions.Views.Allies:
            self.mapVisibiitySelection.setCurrentIndex(1)
        self.mapVisibiitySelection.addItem("Allies Only", ForcedOptions.Views.OnlyAllies)
        if self.game.settings.map_coalition_visibility == ForcedOptions.Views.OnlyAllies:
            self.mapVisibiitySelection.setCurrentIndex(2)
        self.mapVisibiitySelection.addItem("Own Aircraft Only", ForcedOptions.Views.MyAircraft)
        if self.game.settings.map_coalition_visibility == ForcedOptions.Views.MyAircraft:
            self.mapVisibiitySelection.setCurrentIndex(3)
        self.mapVisibiitySelection.addItem("Map Only", ForcedOptions.Views.OnlyMap)
        if self.game.settings.map_coalition_visibility == ForcedOptions.Views.OnlyMap:
            self.mapVisibiitySelection.setCurrentIndex(4)
        self.mapVisibiitySelection.currentIndexChanged.connect(self.applySettings)
        self.difficultyLayout.addWidget(QLabel("Map visibility options"), 5, 0)
        self.difficultyLayout.addWidget(self.mapVisibiitySelection, 5, 1, Qt.AlignRight)

        self.ext_views = QCheckBox()
        self.ext_views.setChecked(self.game.settings.external_views_allowed)
        self.ext_views.toggled.connect(self.applySettings)
        self.difficultyLayout.addWidget(QLabel("Allow external views"), 6, 0)
        self.difficultyLayout.addWidget(self.ext_views, 6, 1, Qt.AlignRight)


    def initGeneratorLayout(self):
        self.generatorPage = QWidget()
        self.generatorLayout = QVBoxLayout()
        self.generatorLayout.setAlignment(Qt.AlignTop)
        self.generatorPage.setLayout(self.generatorLayout)

        self.gameplay = QGroupBox("Gameplay")
        self.gameplayLayout = QGridLayout();
        self.gameplayLayout.setAlignment(Qt.AlignTop)
        self.gameplay.setLayout(self.gameplayLayout)

        self.supercarrier = QCheckBox()
        self.supercarrier.setChecked(self.game.settings.supercarrier)
        self.supercarrier.toggled.connect(self.applySettings)

        self.generate_marks = QCheckBox()
        self.generate_marks.setChecked(self.game.settings.generate_marks)
        self.generate_marks.toggled.connect(self.applySettings)


        if not hasattr(self.game.settings, "include_jtac_if_available"):
            self.game.settings.include_jtac_if_available = True

        self.include_jtac_if_available = QCheckBox()
        self.include_jtac_if_available.setChecked(self.game.settings.include_jtac_if_available)
        self.include_jtac_if_available.toggled.connect(self.applySettings)

        self.gameplayLayout.addWidget(QLabel("Use Supercarrier Module"), 0, 0)
        self.gameplayLayout.addWidget(self.supercarrier, 0, 1, Qt.AlignRight)
        self.gameplayLayout.addWidget(QLabel("Put Objective Markers on Map"), 1, 0)
        self.gameplayLayout.addWidget(self.generate_marks, 1, 1, Qt.AlignRight)
        self.gameplayLayout.addWidget(QLabel("Include JTAC (If available)"), 2, 0)
        self.gameplayLayout.addWidget(self.include_jtac_if_available, 2, 1, Qt.AlignRight)

        self.performance = QGroupBox("Performance")
        self.performanceLayout = QGridLayout()
        self.performanceLayout.setAlignment(Qt.AlignTop)
        self.performance.setLayout(self.performanceLayout)

        self.smoke = QCheckBox()
        self.smoke.setChecked(self.game.settings.perf_smoke_gen)
        self.smoke.toggled.connect(self.applySettings)

        self.red_alert = QCheckBox()
        self.red_alert.setChecked(self.game.settings.perf_red_alert_state)
        self.red_alert.toggled.connect(self.applySettings)

        self.arti = QCheckBox()
        self.arti.setChecked(self.game.settings.perf_artillery)
        self.arti.toggled.connect(self.applySettings)

        self.moving_units = QCheckBox()
        self.moving_units.setChecked(self.game.settings.perf_moving_units)
        self.moving_units.toggled.connect(self.applySettings)

        self.infantry = QCheckBox()
        self.infantry.setChecked(self.game.settings.perf_infantry)
        self.infantry.toggled.connect(self.applySettings)

        self.ai_parking_start = QCheckBox()
        self.ai_parking_start.setChecked(self.game.settings.perf_ai_parking_start)
        self.ai_parking_start.toggled.connect(self.applySettings)

        self.destroyed_units = QCheckBox()
        self.destroyed_units.setChecked(self.game.settings.perf_destroyed_units)
        self.destroyed_units.toggled.connect(self.applySettings)

        self.culling = QCheckBox()
        self.culling.setChecked(self.game.settings.perf_culling)
        self.culling.toggled.connect(self.applySettings)

        self.culling_distance = QSpinBox()
        self.culling_distance.setMinimum(50)
        self.culling_distance.setMaximum(10000)
        self.culling_distance.setValue(self.game.settings.perf_culling_distance)
        self.culling_distance.valueChanged.connect(self.applySettings)

        self.performanceLayout.addWidget(QLabel("Smoke visual effect on frontline"), 0, 0)
        self.performanceLayout.addWidget(self.smoke, 0, 1, alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("SAM starts in RED alert mode"), 1, 0)
        self.performanceLayout.addWidget(self.red_alert, 1, 1, alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Artillery strikes"), 2, 0)
        self.performanceLayout.addWidget(self.arti, 2, 1, alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Moving ground units"), 3, 0)
        self.performanceLayout.addWidget(self.moving_units, 3, 1, alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Generate infantry squads along vehicles"), 4, 0)
        self.performanceLayout.addWidget(self.infantry, 4, 1, alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("AI planes parking start (AI starts in flight if disabled)"), 5, 0)
        self.performanceLayout.addWidget(self.ai_parking_start, 5, 1, alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Include destroyed units carcass"), 6, 0)
        self.performanceLayout.addWidget(self.destroyed_units, 6, 1, alignment=Qt.AlignRight)

        self.performanceLayout.addWidget(QHorizontalSeparationLine(), 7, 0, 1, 2)
        self.performanceLayout.addWidget(QLabel("Culling of distant units enabled"), 8, 0)
        self.performanceLayout.addWidget(self.culling, 8, 1, alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Culling distance (km)"), 9, 0)
        self.performanceLayout.addWidget(self.culling_distance, 9, 1, alignment=Qt.AlignRight)

        self.generatorLayout.addWidget(self.gameplay)
        self.generatorLayout.addWidget(QLabel("Disabling settings below may improve performance, but will impact the overall quality of the experience."))
        self.generatorLayout.addWidget(self.performance)


    def initCheatLayout(self):

        self.cheatPage = QWidget()
        self.cheatLayout = QGridLayout()
        self.cheatPage.setLayout(self.cheatLayout)

        self.moneyCheatBox = QGroupBox("Money Cheat")
        self.moneyCheatBox.setAlignment(Qt.AlignTop)
        self.moneyCheatBoxLayout = QGridLayout()
        self.moneyCheatBox.setLayout(self.moneyCheatBoxLayout)

        self.cheat25M = QPushButton("Cheat +25M")
        self.cheat50M = QPushButton("Cheat +50M")
        self.cheat100M = QPushButton("Cheat +100M")
        self.cheat200M = QPushButton("Cheat +200M")
        self.cheat500M = QPushButton("Cheat +500M")
        self.cheat1000M = QPushButton("Cheat +1000M")

        self.cheat25M.clicked.connect(lambda: self.cheatMoney(25))
        self.cheat50M.clicked.connect(lambda: self.cheatMoney(50))
        self.cheat100M.clicked.connect(lambda: self.cheatMoney(100))
        self.cheat200M.clicked.connect(lambda: self.cheatMoney(200))
        self.cheat500M.clicked.connect(lambda: self.cheatMoney(500))
        self.cheat1000M.clicked.connect(lambda: self.cheatMoney(1000))

        self.moneyCheatBoxLayout.addWidget(self.cheat25M, 0, 0)
        self.moneyCheatBoxLayout.addWidget(self.cheat50M, 0, 1)
        self.moneyCheatBoxLayout.addWidget(self.cheat100M, 1, 0)
        self.moneyCheatBoxLayout.addWidget(self.cheat200M, 1, 1)
        self.moneyCheatBoxLayout.addWidget(self.cheat500M, 2, 0)
        self.moneyCheatBoxLayout.addWidget(self.cheat1000M, 2, 1)

        self.cheatLayout.addWidget(self.moneyCheatBox, 0, 0)

    def cheatMoney(self, amount):
        self.game.budget += amount
        self.game.informations.append(Information("CHEATER", "You are a cheater and you should feel bad", self.game.turn))
        GameUpdateSignal.get_instance().updateGame(self.game)

    def applySettings(self):
        self.game.settings.player_skill = CONST.SKILL_OPTIONS[self.playerCoalitionSkill.currentIndex()]
        self.game.settings.enemy_skill = CONST.SKILL_OPTIONS[self.enemyCoalitionSkill.currentIndex()]
        self.game.settings.enemy_vehicle_skill = CONST.SKILL_OPTIONS[self.enemyAASkill.currentIndex()]
        self.game.settings.labels = CONST.LABELS_OPTIONS[self.difficultyLabel.currentIndex()]
        self.game.settings.night_disabled = self.noNightMission.isChecked()
        self.game.settings.map_coalition_visibility = self.mapVisibiitySelection.currentData()
        self.game.settings.external_views_allowed = self.ext_views.isChecked()
        self.game.settings.generate_marks = self.generate_marks.isChecked()
        self.game.settings.include_jtac_if_available = self.include_jtac_if_available.isChecked()

        print(self.game.settings.map_coalition_visibility)

        self.game.settings.supercarrier = self.supercarrier.isChecked()

        self.game.settings.perf_red_alert_state = self.red_alert.isChecked()
        self.game.settings.perf_smoke_gen = self.smoke.isChecked()
        self.game.settings.perf_artillery = self.arti.isChecked()
        self.game.settings.perf_moving_units = self.moving_units.isChecked()
        self.game.settings.perf_infantry = self.infantry.isChecked()
        self.game.settings.perf_ai_parking_start = self.ai_parking_start.isChecked()
        self.game.settings.perf_destroyed_units = self.destroyed_units.isChecked()

        self.game.settings.perf_culling = self.culling.isChecked()
        self.game.settings.perf_culling_distance = int(self.culling_distance.value())

        GameUpdateSignal.get_instance().updateGame(self.game)

    def onSelectionChanged(self):
        index = self.categoryList.selectionModel().currentIndex().row()
        self.right_layout.setCurrentIndex(index)
예제 #23
0
class LabelConfigurator(QDialog):
    def __init__(self, boxManager, spawnPos):
        super().__init__()
        # Variables
        self.spawnPos = spawnPos

        # Objects
        self.boxManager = boxManager
        self.layout = QVBoxLayout(self)
        self.contentLayout = QHBoxLayout()
        self.settingsLayout = QVBoxLayout()
        self.isOccludedButton = Check('Occluded',
                                      boxManager.getRecentIsOccluded())
        self.isTruncatedButton = Check('Truncated',
                                       boxManager.getRecentIsTruncated())
        self.isGroupOfButton = Check('Group Of',
                                     boxManager.getRecentIsGroupOf())
        self.isDepictionButton = Check('Depiction',
                                       boxManager.getRecentIsDepiction())
        self.isInsideButton = Check('Inside', boxManager.getRecentIsInside())
        self.acceptButton = QPushButton('Accept')
        self.cancelButton = QPushButton('Cancel')
        self.labelsModel = QStringListModel()
        self.labelsView = QListView()

        # Layout
        self.setWindowFlags(Qt.Popup)
        self.settingsLayout.setAlignment(Qt.AlignTop | Qt.AlignCenter)
        self.settingsLayout.setMargin(0)
        self.settingsLayout.addWidget(self.isOccludedButton)
        self.settingsLayout.addWidget(self.isTruncatedButton)
        self.settingsLayout.addWidget(self.isGroupOfButton)
        self.settingsLayout.addWidget(self.isDepictionButton)
        self.settingsLayout.addWidget(self.isInsideButton)
        self.settingsLayout.addStretch(1)
        self.settingsLayout.addWidget(self.acceptButton)
        self.settingsLayout.addWidget(self.cancelButton)
        self.contentLayout.addWidget(self.labelsView)
        self.contentLayout.addLayout(self.settingsLayout)
        self.layout.addLayout(self.contentLayout)

        # Styling
        self.setStyleSheet('LabelConfigurator { '
                           'background-color: ' + ThemeManager.BG_L1 + ';'
                           'border-top-left-radius:     ' +
                           str(ThemeManager.CURVE) + 'px;'
                           'border-bottom-left-radius:  ' +
                           str(ThemeManager.CURVE) + 'px;'
                           'border-top-right-radius:    ' +
                           str(ThemeManager.CURVE) + 'px;'
                           'border-bottom-right-radius: ' +
                           str(ThemeManager.CURVE) + 'px;'
                           'border-width: 0px;'
                           'border-style: solid;'
                           '}'
                           'QPushButton {'
                           'background-color: ' + ThemeManager.BG_L2 + ';'
                           'border-radius: 10px;'
                           'color: ' + ThemeManager.LABEL + ';'
                           'font-size: 14px;'
                           '}'
                           'QPushButton:hover {'
                           'background-color: ' + ThemeManager.BG_L3 + ';'
                           '}'
                           'QListView { '
                           'background-color: ' + ThemeManager.BG_L2 + ';'
                           '}')
        self.layout.setMargin(20)
        self.layout.setSpacing(10)
        self.contentLayout.setMargin(0)
        self.labelsModel.setStringList(boxManager.loadLabels())
        self.labelsView.setFixedWidth(80)
        self.labelsView.setFrameStyle(QFrame.NoFrame)
        self.labelsView.setModel(self.labelsModel)
        self.labelsView.setItemDelegate(ListDelegate.ListDelegate())

        index = None
        try:
            row = self.labelsModel.stringList().index(
                boxManager.getRecentLabelName())
            index = self.labelsModel.index(row)
        except ValueError:
            index = self.labelsModel.index(0)
        if index is not None:
            self.labelsView.setCurrentIndex(index)

        # Connections
        self.acceptButton.clicked.connect(self.close)
        self.cancelButton.clicked.connect(self.reject)

    def showEvent(self, event):
        super().showEvent(event)
        self.move(self.spawnPos)

    def closeEvent(self, event):
        labelConfig = (self.labelsView.selectedIndexes()[0].data(
            role=Qt.DisplayRole), self.isOccludedButton.getEnabled(),
                       self.isTruncatedButton.getEnabled(),
                       self.isGroupOfButton.getEnabled(),
                       self.isDepictionButton.getEnabled(),
                       self.isInsideButton.getEnabled())
        self.labelAccepted.emit(labelConfig)
        super().closeEvent(event)

    def getLabelConfig(self):
        return

    labelAccepted = Signal(object)
예제 #24
0
from PySide2.QtCore import QStringListModel
from PySide2.QtWidgets import QApplication, QListView, QComboBox

if __name__ == '__main__':
    """
    Using a model for two different views
    Now the changes in QListView will be shown in QComboBox
    """

    app = QApplication(sys.argv)

    # Let's make the QListWidget show this data
    data = ["ONE", "TWO", "THREE", "FOUR", "FIVE"]

    list_widget = QListView()
    list_widget.show()

    model = QStringListModel(data)

    # Setting the model to our QListView
    list_widget.setModel(model)

    # Another view
    comboBox = QComboBox()
    comboBox.show()

    # The new view uses the same model
    comboBox.setModel(model)

    sys.exit(app.exec_())
예제 #25
0
    foods = [
        'Cookie dough',  # Must be store-bought
        'Hummus',  # Must be homemade
        'Spaghetti',  # Must be saucy
        'Dal makhani',  # Must be spicy
        'Chocolate whipped cream'  # Must be plentiful
    ]

    for food in foods:
        # Create an item with a caption
        item = QStandardItem(food)

        # Add a checkbox to it
        item.setCheckable(True)

        # Add the item to the model
        #model.appendRow(item)
    item = QStandardItem(ledit)
    model.appendRow(item)
    listView.setModel(model)

    browser.load(QUrl('http://avito.ru'))

    grid.addWidget(listView, 0, 1)
    grid.addWidget(browser, 0, 2)

    main_frame.setLayout(grid)
    main_frame.show()
    sys.exit(app.exec_())
예제 #26
0
class SourceCodeManager:
    def __init__(self, window):
        self.text_edit = QtGui.QTextEdit(window)
        self.text_edit.setReadOnly(True)
        # FIXME: write an optimized model
        self.traceback = None
        self.traceback_model = QStringListModel()
        self.traceback_view = QListView(window)
        self.traceback_view.setModel(self.traceback_model)
        self.traceback_view.setEditTriggers(
            QtGui.QAbstractItemView.NoEditTriggers)
        window.connect(
            self.traceback_view.selectionModel(),
            QtCore.SIGNAL(
                "selectionChanged(const QItemSelection&, const QItemSelection&)"
            ), self.frame_selection_changed)
        # filename => (lines, mtime)
        self._file_cache = {}
        self.clear()

    def clear(self):
        self._current_file = None
        self._current_lineno = None
        self.traceback_model.setStringList([])
        self.text_edit.setText('')
        self._file_cache.clear()

    def frame_selection_changed(self, selected, unselected):
        indexes = selected.indexes()
        if not indexes:
            return
        row = indexes[0].row()
        frame = self.traceback[row]
        self.show_frame(frame)

    def set_traceback(self, traceback, show_lineno):
        self.traceback = traceback
        if show_lineno:
            lines = [
                '%s:%s' % (frame.filename, frame.lineno) for frame in traceback
            ]
        else:
            lines = [frame.filename for frame in traceback]
        self.traceback_model.setStringList(lines)

    def read_file(self, filename):
        try:
            mtime = os.stat(filename).st_mtime
        except OSError:
            return None

        if filename in self._file_cache:
            text, cache_mtime = self._file_cache[filename]
            if mtime == cache_mtime:
                return text

        print("Read %s content (mtime: %s)" % (filename, mtime))
        with open(filename, 'rb') as fp:
            encoding, lines = detect_encoding(fp.readline)
        lineno = 1
        lines = []
        with io.open(filename, 'r', encoding=encoding) as fp:
            for lineno, line in enumerate(fp, 1):
                lines.append('%d: %s' % (lineno, line.rstrip()))

        text = '\n'.join(lines)
        self._file_cache[filename] = (text, mtime)
        return text

    def load_file(self, filename):
        if filename.startswith("<") and filename.startswith(">"):
            return False
        if self._current_file == filename:
            return True
        text = self.read_file(filename)
        if text is None:
            return False
        self.text_edit.setText(text)
        self._current_file = filename
        self._current_lineno = None
        return True

    def set_line_number(self, lineno):
        if self._current_lineno == lineno:
            return
        self._current_lineno = lineno
        doc = self.text_edit.document()
        # FIXME: complexity in O(number of lines)?
        block = doc.findBlockByLineNumber(lineno - 1)
        cursor = QTextCursor(block)
        cursor.select(QTextCursor.BlockUnderCursor)
        # FIXME: complexity in O(number of lines)?
        self.text_edit.setTextCursor(cursor)

    def show_frame(self, frame):
        filename = frame.filename
        if not self.load_file(filename):
            self._current_file = None
            self.text_edit.setText('')
            return
        if frame.lineno > 0:
            self.set_line_number(frame.lineno)
예제 #27
0
class QSettingsWindow(QDialog):
    def __init__(self, game: Game):
        super(QSettingsWindow, self).__init__()

        self.game = game
        self.pluginsPage = None
        self.pluginsOptionsPage = None
        self.campaign_management_page = QWidget()

        self.setModal(True)
        self.setWindowTitle("Settings")
        self.setWindowIcon(CONST.ICONS["Settings"])
        self.setMinimumSize(600, 250)

        self.initUi()

    def initUi(self):
        self.layout = QGridLayout()

        self.categoryList = QListView()
        self.right_layout = QStackedLayout()

        self.categoryList.setMaximumWidth(175)

        self.categoryModel = QStandardItemModel(self.categoryList)

        self.categoryList.setIconSize(QSize(32, 32))

        self.initDifficultyLayout()
        difficulty = QStandardItem("Difficulty")
        difficulty.setIcon(CONST.ICONS["Missile"])
        difficulty.setEditable(False)
        difficulty.setSelectable(True)
        self.categoryModel.appendRow(difficulty)
        self.right_layout.addWidget(self.difficultyPage)

        self.init_campaign_management_layout()
        campaign_management = QStandardItem("Campaign Management")
        campaign_management.setIcon(CONST.ICONS["Money"])
        campaign_management.setEditable(False)
        campaign_management.setSelectable(True)
        self.categoryModel.appendRow(campaign_management)
        self.right_layout.addWidget(self.campaign_management_page)

        self.initGeneratorLayout()
        generator = QStandardItem("Mission Generator")
        generator.setIcon(CONST.ICONS["Generator"])
        generator.setEditable(False)
        generator.setSelectable(True)
        self.categoryModel.appendRow(generator)
        self.right_layout.addWidget(self.generatorPage)

        self.initCheatLayout()
        cheat = QStandardItem("Cheat Menu")
        cheat.setIcon(CONST.ICONS["Cheat"])
        cheat.setEditable(False)
        cheat.setSelectable(True)
        self.categoryModel.appendRow(cheat)
        self.right_layout.addWidget(self.cheatPage)

        self.pluginsPage = PluginsPage()
        plugins = QStandardItem("LUA Plugins")
        plugins.setIcon(CONST.ICONS["Plugins"])
        plugins.setEditable(False)
        plugins.setSelectable(True)
        self.categoryModel.appendRow(plugins)
        self.right_layout.addWidget(self.pluginsPage)

        self.pluginsOptionsPage = PluginOptionsPage()
        pluginsOptions = QStandardItem("LUA Plugins Options")
        pluginsOptions.setIcon(CONST.ICONS["PluginsOptions"])
        pluginsOptions.setEditable(False)
        pluginsOptions.setSelectable(True)
        self.categoryModel.appendRow(pluginsOptions)
        self.right_layout.addWidget(self.pluginsOptionsPage)

        self.categoryList.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.categoryList.setModel(self.categoryModel)
        self.categoryList.selectionModel().setCurrentIndex(
            self.categoryList.indexAt(QPoint(1, 1)),
            QItemSelectionModel.Select)
        self.categoryList.selectionModel().selectionChanged.connect(
            self.onSelectionChanged)

        self.layout.addWidget(self.categoryList, 0, 0, 1, 1)
        self.layout.addLayout(self.right_layout, 0, 1, 5, 1)

        self.setLayout(self.layout)

    def init(self):
        pass

    def initDifficultyLayout(self):

        self.difficultyPage = QWidget()
        self.difficultyLayout = QVBoxLayout()
        self.difficultyLayout.setAlignment(Qt.AlignTop)
        self.difficultyPage.setLayout(self.difficultyLayout)

        # DCS AI difficulty settings
        self.aiDifficultySettings = QGroupBox("AI Difficulty")
        self.aiDifficultyLayout = QGridLayout()
        self.playerCoalitionSkill = QComboBox()
        self.enemyCoalitionSkill = QComboBox()
        self.enemyAASkill = QComboBox()
        for skill in CONST.SKILL_OPTIONS:
            self.playerCoalitionSkill.addItem(skill)
            self.enemyCoalitionSkill.addItem(skill)
            self.enemyAASkill.addItem(skill)

        self.playerCoalitionSkill.setCurrentIndex(
            CONST.SKILL_OPTIONS.index(self.game.settings.player_skill))
        self.enemyCoalitionSkill.setCurrentIndex(
            CONST.SKILL_OPTIONS.index(self.game.settings.enemy_skill))
        self.enemyAASkill.setCurrentIndex(
            CONST.SKILL_OPTIONS.index(self.game.settings.enemy_vehicle_skill))

        self.player_income = TenthsSpinSlider(
            "Player income multiplier",
            0,
            50,
            int(self.game.settings.player_income_multiplier * 10),
        )
        self.player_income.spinner.valueChanged.connect(self.applySettings)
        self.enemy_income = TenthsSpinSlider(
            "Enemy income multiplier",
            0,
            50,
            int(self.game.settings.enemy_income_multiplier * 10),
        )
        self.enemy_income.spinner.valueChanged.connect(self.applySettings)

        self.playerCoalitionSkill.currentIndexChanged.connect(
            self.applySettings)
        self.enemyCoalitionSkill.currentIndexChanged.connect(
            self.applySettings)
        self.enemyAASkill.currentIndexChanged.connect(self.applySettings)

        # Mission generation settings related to difficulty
        self.missionSettings = QGroupBox("Mission Difficulty")
        self.missionLayout = QGridLayout()

        self.manpads = QCheckBox()
        self.manpads.setChecked(self.game.settings.manpads)
        self.manpads.toggled.connect(self.applySettings)

        self.noNightMission = QCheckBox()
        self.noNightMission.setChecked(self.game.settings.night_disabled)
        self.noNightMission.toggled.connect(self.applySettings)

        # DCS Mission options
        self.missionRestrictionsSettings = QGroupBox("Mission Restrictions")
        self.missionRestrictionsLayout = QGridLayout()

        self.difficultyLabel = QComboBox()
        [self.difficultyLabel.addItem(t) for t in CONST.LABELS_OPTIONS]
        self.difficultyLabel.setCurrentIndex(
            CONST.LABELS_OPTIONS.index(self.game.settings.labels))
        self.difficultyLabel.currentIndexChanged.connect(self.applySettings)

        self.mapVisibiitySelection = QComboBox()
        self.mapVisibiitySelection.addItem("All", ForcedOptions.Views.All)
        if self.game.settings.map_coalition_visibility == ForcedOptions.Views.All:
            self.mapVisibiitySelection.setCurrentIndex(0)
        self.mapVisibiitySelection.addItem("Fog of War",
                                           ForcedOptions.Views.Allies)
        if self.game.settings.map_coalition_visibility == ForcedOptions.Views.Allies:
            self.mapVisibiitySelection.setCurrentIndex(1)
        self.mapVisibiitySelection.addItem("Allies Only",
                                           ForcedOptions.Views.OnlyAllies)
        if (self.game.settings.map_coalition_visibility ==
                ForcedOptions.Views.OnlyAllies):
            self.mapVisibiitySelection.setCurrentIndex(2)
        self.mapVisibiitySelection.addItem("Own Aircraft Only",
                                           ForcedOptions.Views.MyAircraft)
        if (self.game.settings.map_coalition_visibility ==
                ForcedOptions.Views.MyAircraft):
            self.mapVisibiitySelection.setCurrentIndex(3)
        self.mapVisibiitySelection.addItem("Map Only",
                                           ForcedOptions.Views.OnlyMap)
        if self.game.settings.map_coalition_visibility == ForcedOptions.Views.OnlyMap:
            self.mapVisibiitySelection.setCurrentIndex(4)
        self.mapVisibiitySelection.currentIndexChanged.connect(
            self.applySettings)

        self.ext_views = QCheckBox()
        self.ext_views.setChecked(self.game.settings.external_views_allowed)
        self.ext_views.toggled.connect(self.applySettings)

        self.aiDifficultyLayout.addWidget(QLabel("Player coalition skill"), 0,
                                          0)
        self.aiDifficultyLayout.addWidget(self.playerCoalitionSkill, 0, 1,
                                          Qt.AlignRight)
        self.aiDifficultyLayout.addWidget(QLabel("Enemy coalition skill"), 1,
                                          0)
        self.aiDifficultyLayout.addWidget(self.enemyCoalitionSkill, 1, 1,
                                          Qt.AlignRight)
        self.aiDifficultyLayout.addWidget(
            QLabel("Enemy AA and vehicles skill"), 2, 0)
        self.aiDifficultyLayout.addWidget(self.enemyAASkill, 2, 1,
                                          Qt.AlignRight)
        self.aiDifficultyLayout.addLayout(self.player_income, 3, 0)
        self.aiDifficultyLayout.addLayout(self.enemy_income, 4, 0)
        self.aiDifficultySettings.setLayout(self.aiDifficultyLayout)
        self.difficultyLayout.addWidget(self.aiDifficultySettings)

        self.missionLayout.addWidget(QLabel("Manpads on frontlines"), 0, 0)
        self.missionLayout.addWidget(self.manpads, 0, 1, Qt.AlignRight)
        self.missionLayout.addWidget(QLabel("No night missions"), 1, 0)
        self.missionLayout.addWidget(self.noNightMission, 1, 1, Qt.AlignRight)
        self.missionSettings.setLayout(self.missionLayout)
        self.difficultyLayout.addWidget(self.missionSettings)

        self.missionRestrictionsLayout.addWidget(QLabel("In Game Labels"), 0,
                                                 0)
        self.missionRestrictionsLayout.addWidget(self.difficultyLabel, 0, 1,
                                                 Qt.AlignRight)
        self.missionRestrictionsLayout.addWidget(
            QLabel("Map visibility options"), 1, 0)
        self.missionRestrictionsLayout.addWidget(self.mapVisibiitySelection, 1,
                                                 1, Qt.AlignRight)
        self.missionRestrictionsLayout.addWidget(
            QLabel("Allow external views"), 2, 0)
        self.missionRestrictionsLayout.addWidget(self.ext_views, 2, 1,
                                                 Qt.AlignRight)
        self.missionRestrictionsSettings.setLayout(
            self.missionRestrictionsLayout)
        self.difficultyLayout.addWidget(self.missionRestrictionsSettings)

    def init_campaign_management_layout(self) -> None:
        campaign_layout = QVBoxLayout()
        campaign_layout.setAlignment(Qt.AlignTop)
        self.campaign_management_page.setLayout(campaign_layout)

        general = QGroupBox("General")
        campaign_layout.addWidget(general)

        general_layout = QGridLayout()
        general.setLayout(general_layout)

        def set_restict_weapons_by_date(value: bool) -> None:
            self.game.settings.restrict_weapons_by_date = value

        restrict_weapons = QCheckBox()
        restrict_weapons.setChecked(
            self.game.settings.restrict_weapons_by_date)
        restrict_weapons.toggled.connect(set_restict_weapons_by_date)

        tooltip_text = (
            "Restricts weapon availability based on the campaign date. Data is "
            "extremely incomplete so does not affect all weapons.")
        restrict_weapons.setToolTip(tooltip_text)
        restrict_weapons_label = QLabel("Restrict weapons by date (WIP)")
        restrict_weapons_label.setToolTip(tooltip_text)

        general_layout.addWidget(restrict_weapons_label, 0, 0)
        general_layout.addWidget(restrict_weapons, 0, 1, Qt.AlignRight)

        def set_old_awec(value: bool) -> None:
            self.game.settings.disable_legacy_aewc = value

        old_awac = QCheckBox()
        old_awac.setChecked(self.game.settings.disable_legacy_aewc)
        old_awac.toggled.connect(set_old_awec)

        old_awec_info = (
            "If checked, the invulnerable friendly AEW&C aircraft that begins "
            "the mission in the air will not be spawned. AEW&C missions must "
            "be planned in the ATO and will take time to arrive on-station.")

        old_awac.setToolTip(old_awec_info)
        old_awac_label = QLabel(
            "Disable invulnerable, always-available AEW&C (WIP)")
        old_awac_label.setToolTip(old_awec_info)

        general_layout.addWidget(old_awac_label, 1, 0)
        general_layout.addWidget(old_awac, 1, 1, Qt.AlignRight)

        automation = QGroupBox("HQ Automation")
        campaign_layout.addWidget(automation)

        automation_layout = QGridLayout()
        automation.setLayout(automation_layout)

        def set_runway_automation(value: bool) -> None:
            self.game.settings.automate_runway_repair = value

        def set_front_line_automation(value: bool) -> None:
            self.game.settings.automate_front_line_reinforcements = value

        def set_aircraft_automation(value: bool) -> None:
            self.game.settings.automate_aircraft_reinforcements = value

        runway_repair = QCheckBox()
        runway_repair.setChecked(self.game.settings.automate_runway_repair)
        runway_repair.toggled.connect(set_runway_automation)

        automation_layout.addWidget(QLabel("Automate runway repairs"), 0, 0)
        automation_layout.addWidget(runway_repair, 0, 1, Qt.AlignRight)

        front_line = QCheckBox()
        front_line.setChecked(
            self.game.settings.automate_front_line_reinforcements)
        front_line.toggled.connect(set_front_line_automation)

        automation_layout.addWidget(QLabel("Automate front-line purchases"), 1,
                                    0)
        automation_layout.addWidget(front_line, 1, 1, Qt.AlignRight)

        aircraft = QCheckBox()
        aircraft.setChecked(
            self.game.settings.automate_aircraft_reinforcements)
        aircraft.toggled.connect(set_aircraft_automation)

        automation_layout.addWidget(QLabel("Automate aircraft purchases"), 2,
                                    0)
        automation_layout.addWidget(aircraft, 2, 1, Qt.AlignRight)

    def initGeneratorLayout(self):
        self.generatorPage = QWidget()
        self.generatorLayout = QVBoxLayout()
        self.generatorLayout.setAlignment(Qt.AlignTop)
        self.generatorPage.setLayout(self.generatorLayout)

        self.gameplay = QGroupBox("Gameplay")
        self.gameplayLayout = QGridLayout()
        self.gameplayLayout.setAlignment(Qt.AlignTop)
        self.gameplay.setLayout(self.gameplayLayout)

        self.supercarrier = QCheckBox()
        self.supercarrier.setChecked(self.game.settings.supercarrier)
        self.supercarrier.toggled.connect(self.applySettings)

        self.generate_marks = QCheckBox()
        self.generate_marks.setChecked(self.game.settings.generate_marks)
        self.generate_marks.toggled.connect(self.applySettings)

        self.generate_dark_kneeboard = QCheckBox()
        self.generate_dark_kneeboard.setChecked(
            self.game.settings.generate_dark_kneeboard)
        self.generate_dark_kneeboard.toggled.connect(self.applySettings)

        self.never_delay_players = QCheckBox()
        self.never_delay_players.setChecked(
            self.game.settings.never_delay_player_flights)
        self.never_delay_players.toggled.connect(self.applySettings)
        self.never_delay_players.setToolTip(
            "When checked, player flights with a delayed start time will be "
            "spawned immediately. AI wingmen may begin startup immediately.")

        self.gameplayLayout.addWidget(QLabel("Use Supercarrier Module"), 0, 0)
        self.gameplayLayout.addWidget(self.supercarrier, 0, 1, Qt.AlignRight)
        self.gameplayLayout.addWidget(QLabel("Put Objective Markers on Map"),
                                      1, 0)
        self.gameplayLayout.addWidget(self.generate_marks, 1, 1, Qt.AlignRight)

        dark_kneeboard_label = QLabel(
            "Generate Dark Kneeboard <br />"
            "<strong>Dark kneeboard for night missions.<br />"
            "This will likely make the kneeboard on the pilot leg unreadable.</strong>"
        )
        self.gameplayLayout.addWidget(dark_kneeboard_label, 2, 0)
        self.gameplayLayout.addWidget(self.generate_dark_kneeboard, 2, 1,
                                      Qt.AlignRight)

        spawn_players_immediately_tooltip = (
            "Always spawns player aircraft immediately, even if their start time is "
            "more than 10 minutes after the start of the mission. <strong>This does "
            "not alter the timing of your mission. Your TOT will not change. This "
            "option only allows the player to wait on the ground.</strong>")
        spawn_immediately_label = QLabel(
            "Player flights ignore TOT and spawn immediately<br />"
            "<strong>Does not adjust package waypoint times.<br />"
            "Should not be used if players have runway or in-air starts.</strong>"
        )
        spawn_immediately_label.setToolTip(spawn_players_immediately_tooltip)
        self.gameplayLayout.addWidget(spawn_immediately_label, 3, 0)
        self.gameplayLayout.addWidget(self.never_delay_players, 3, 1,
                                      Qt.AlignRight)

        start_type_label = QLabel(
            "Default start type for AI aircraft<br /><strong>Warning: "
            "Any option other than Cold breaks OCA/Aircraft missions.</strong>"
        )
        start_type_label.setToolTip(START_TYPE_TOOLTIP)
        start_type = StartTypeComboBox(self.game.settings)
        start_type.setCurrentText(self.game.settings.default_start_type)

        self.gameplayLayout.addWidget(start_type_label, 4, 0)
        self.gameplayLayout.addWidget(start_type, 4, 1)

        self.performance = QGroupBox("Performance")
        self.performanceLayout = QGridLayout()
        self.performanceLayout.setAlignment(Qt.AlignTop)
        self.performance.setLayout(self.performanceLayout)

        self.smoke = QCheckBox()
        self.smoke.setChecked(self.game.settings.perf_smoke_gen)
        self.smoke.toggled.connect(self.applySettings)

        self.red_alert = QCheckBox()
        self.red_alert.setChecked(self.game.settings.perf_red_alert_state)
        self.red_alert.toggled.connect(self.applySettings)

        self.arti = QCheckBox()
        self.arti.setChecked(self.game.settings.perf_artillery)
        self.arti.toggled.connect(self.applySettings)

        self.moving_units = QCheckBox()
        self.moving_units.setChecked(self.game.settings.perf_moving_units)
        self.moving_units.toggled.connect(self.applySettings)

        self.infantry = QCheckBox()
        self.infantry.setChecked(self.game.settings.perf_infantry)
        self.infantry.toggled.connect(self.applySettings)

        self.destroyed_units = QCheckBox()
        self.destroyed_units.setChecked(
            self.game.settings.perf_destroyed_units)
        self.destroyed_units.toggled.connect(self.applySettings)

        self.culling = QCheckBox()
        self.culling.setChecked(self.game.settings.perf_culling)
        self.culling.toggled.connect(self.applySettings)

        self.culling_distance = QSpinBox()
        self.culling_distance.setMinimum(10)
        self.culling_distance.setMaximum(10000)
        self.culling_distance.setValue(
            self.game.settings.perf_culling_distance)
        self.culling_distance.valueChanged.connect(self.applySettings)

        self.culling_do_not_cull_carrier = QCheckBox()
        self.culling_do_not_cull_carrier.setChecked(
            self.game.settings.perf_do_not_cull_carrier)
        self.culling_do_not_cull_carrier.toggled.connect(self.applySettings)

        self.performanceLayout.addWidget(
            QLabel("Smoke visual effect on frontline"), 0, 0)
        self.performanceLayout.addWidget(self.smoke,
                                         0,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(
            QLabel("SAM starts in RED alert mode"), 1, 0)
        self.performanceLayout.addWidget(self.red_alert,
                                         1,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Artillery strikes"), 2, 0)
        self.performanceLayout.addWidget(self.arti,
                                         2,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Moving ground units"), 3, 0)
        self.performanceLayout.addWidget(self.moving_units,
                                         3,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(
            QLabel("Generate infantry squads along vehicles"), 4, 0)
        self.performanceLayout.addWidget(self.infantry,
                                         4,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(
            QLabel("Include destroyed units carcass"), 6, 0)
        self.performanceLayout.addWidget(self.destroyed_units,
                                         6,
                                         1,
                                         alignment=Qt.AlignRight)

        self.performanceLayout.addWidget(QHorizontalSeparationLine(), 7, 0, 1,
                                         2)
        self.performanceLayout.addWidget(
            QLabel("Culling of distant units enabled"), 8, 0)
        self.performanceLayout.addWidget(self.culling,
                                         8,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Culling distance (km)"), 9, 0)
        self.performanceLayout.addWidget(self.culling_distance,
                                         9,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(
            QLabel("Do not cull carrier's surroundings"), 10, 0)
        self.performanceLayout.addWidget(self.culling_do_not_cull_carrier,
                                         10,
                                         1,
                                         alignment=Qt.AlignRight)

        self.generatorLayout.addWidget(self.gameplay)
        self.generatorLayout.addWidget(
            QLabel(
                "Disabling settings below may improve performance, but will impact the overall quality of the experience."
            ))
        self.generatorLayout.addWidget(self.performance)

    def initCheatLayout(self):

        self.cheatPage = QWidget()
        self.cheatLayout = QVBoxLayout()
        self.cheatPage.setLayout(self.cheatLayout)

        self.cheat_options = CheatSettingsBox(self.game, self.applySettings)
        self.cheatLayout.addWidget(self.cheat_options)

        self.moneyCheatBox = QGroupBox("Money Cheat")
        self.moneyCheatBox.setAlignment(Qt.AlignTop)
        self.moneyCheatBoxLayout = QGridLayout()
        self.moneyCheatBox.setLayout(self.moneyCheatBoxLayout)

        cheats_amounts = [25, 50, 100, 200, 500, 1000, -25, -50, -100, -200]
        for i, amount in enumerate(cheats_amounts):
            if amount > 0:
                btn = QPushButton("Cheat +" + str(amount) + "M")
                btn.setProperty("style", "btn-success")
            else:
                btn = QPushButton("Cheat " + str(amount) + "M")
                btn.setProperty("style", "btn-danger")
            btn.clicked.connect(self.cheatLambda(amount))
            self.moneyCheatBoxLayout.addWidget(btn, i / 2, i % 2)
        self.cheatLayout.addWidget(self.moneyCheatBox, stretch=1)

    def cheatLambda(self, amount):
        return lambda: self.cheatMoney(amount)

    def cheatMoney(self, amount):
        logging.info("CHEATING FOR AMOUNT : " + str(amount) + "M")
        self.game.budget += amount
        if amount > 0:
            self.game.informations.append(
                Information(
                    "CHEATER",
                    "You are a cheater and you should feel bad",
                    self.game.turn,
                ))
        else:
            self.game.informations.append(
                Information("CHEATER", "You are still a cheater !",
                            self.game.turn))
        GameUpdateSignal.get_instance().updateGame(self.game)

    def applySettings(self):
        self.game.settings.player_skill = CONST.SKILL_OPTIONS[
            self.playerCoalitionSkill.currentIndex()]
        self.game.settings.enemy_skill = CONST.SKILL_OPTIONS[
            self.enemyCoalitionSkill.currentIndex()]
        self.game.settings.enemy_vehicle_skill = CONST.SKILL_OPTIONS[
            self.enemyAASkill.currentIndex()]
        self.game.settings.player_income_multiplier = self.player_income.value
        self.game.settings.enemy_income_multiplier = self.enemy_income.value
        self.game.settings.manpads = self.manpads.isChecked()
        self.game.settings.labels = CONST.LABELS_OPTIONS[
            self.difficultyLabel.currentIndex()]
        self.game.settings.night_disabled = self.noNightMission.isChecked()
        self.game.settings.map_coalition_visibility = (
            self.mapVisibiitySelection.currentData())
        self.game.settings.external_views_allowed = self.ext_views.isChecked()
        self.game.settings.generate_marks = self.generate_marks.isChecked()
        self.game.settings.never_delay_player_flights = (
            self.never_delay_players.isChecked())

        self.game.settings.supercarrier = self.supercarrier.isChecked()

        self.game.settings.generate_dark_kneeboard = (
            self.generate_dark_kneeboard.isChecked())

        self.game.settings.perf_red_alert_state = self.red_alert.isChecked()
        self.game.settings.perf_smoke_gen = self.smoke.isChecked()
        self.game.settings.perf_artillery = self.arti.isChecked()
        self.game.settings.perf_moving_units = self.moving_units.isChecked()
        self.game.settings.perf_infantry = self.infantry.isChecked()
        self.game.settings.perf_destroyed_units = self.destroyed_units.isChecked(
        )

        self.game.settings.perf_culling = self.culling.isChecked()
        self.game.settings.perf_culling_distance = int(
            self.culling_distance.value())
        self.game.settings.perf_do_not_cull_carrier = (
            self.culling_do_not_cull_carrier.isChecked())

        self.game.settings.show_red_ato = self.cheat_options.show_red_ato
        self.game.settings.enable_frontline_cheats = (
            self.cheat_options.show_frontline_cheat)
        self.game.settings.enable_base_capture_cheat = (
            self.cheat_options.show_base_capture_cheat)

        self.game.compute_conflicts_position()
        GameUpdateSignal.get_instance().updateGame(self.game)

    def onSelectionChanged(self):
        index = self.categoryList.selectionModel().currentIndex().row()
        self.right_layout.setCurrentIndex(index)
예제 #28
0
class IconColorEditor(QDialog):
    """An editor to let the user select an icon and a color for an object_class.
    """
    def __init__(self, parent):
        """Init class."""
        super().__init__(parent)  # , Qt.Popup)
        icon_size = QSize(32, 32)
        self.icon_mngr = IconListManager(icon_size)
        self.setWindowTitle("Select icon and color")
        self.icon_widget = QWidget(self)
        self.icon_list = QListView(self.icon_widget)
        self.icon_list.setViewMode(QListView.IconMode)
        self.icon_list.setIconSize(icon_size)
        self.icon_list.setResizeMode(QListView.Adjust)
        self.icon_list.setItemDelegate(_IconPainterDelegate(self))
        self.icon_list.setMovement(QListView.Static)
        self.icon_list.setMinimumHeight(400)
        icon_widget_layout = QVBoxLayout(self.icon_widget)
        icon_widget_layout.addWidget(QLabel("Font Awesome icons"))
        self.line_edit = QLineEdit()
        self.line_edit.setPlaceholderText("Search icons for...")
        icon_widget_layout.addWidget(self.line_edit)
        icon_widget_layout.addWidget(self.icon_list)
        self.color_dialog = QColorDialog(self)
        self.color_dialog.setWindowFlags(Qt.Widget)
        self.color_dialog.setOption(QColorDialog.NoButtons, True)
        self.color_dialog.setOption(QColorDialog.DontUseNativeDialog, True)
        self.button_box = QDialogButtonBox(self)
        self.button_box.setStandardButtons(QDialogButtonBox.Cancel
                                           | QDialogButtonBox.Ok)
        top_widget = QWidget(self)
        top_layout = QHBoxLayout(top_widget)
        top_layout.addWidget(self.icon_widget)
        top_layout.addWidget(self.color_dialog)
        layout = QVBoxLayout(self)
        layout.addWidget(top_widget)
        layout.addWidget(self.button_box)
        self.proxy_model = QSortFilterProxyModel(self)
        self.proxy_model.setSourceModel(self.icon_mngr.model)
        self.proxy_model.filterAcceptsRow = self._proxy_model_filter_accepts_row
        self.icon_list.setModel(self.proxy_model)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.connect_signals()

    def _proxy_model_filter_accepts_row(self, source_row, source_parent):
        """Overridden method to filter icons according to search terms.
        """
        text = self.line_edit.text()
        if not text:
            return QSortFilterProxyModel.filterAcceptsRow(
                self.proxy_model, source_row, source_parent)
        searchterms = self.icon_mngr.model.index(
            source_row, 0, source_parent).data(Qt.UserRole + 1)
        return any([text in term for term in searchterms])

    def connect_signals(self):
        """Connect signals to slots."""
        self.line_edit.textEdited.connect(self.proxy_model.invalidateFilter)
        self.button_box.accepted.connect(self.accept)
        self.button_box.rejected.connect(self.reject)

    def set_data(self, data):
        icon_code, color_code = interpret_icon_id(data)
        self.icon_mngr.init_model()
        for i in range(self.proxy_model.rowCount()):
            index = self.proxy_model.index(i, 0)
            if index.data(Qt.UserRole) == icon_code:
                self.icon_list.setCurrentIndex(index)
                break
        self.color_dialog.setCurrentColor(QColor(color_code))

    def data(self):
        icon_code = self.icon_list.currentIndex().data(Qt.UserRole)
        color_code = self.color_dialog.currentColor().rgb()
        return make_icon_id(icon_code, color_code)
예제 #29
0
class ClipboardManager:
    def __init__(self):
        self.clips = []
        self.clipboard_save_dir = _dir / "clip"
        self.app_settings_file = Path(
            QStandardPaths.writableLocation(
                QStandardPaths.GenericConfigLocation)
        ) / "network_clipboard_settings.json"
        if self.app_settings_file.exists():
            self.clipboard_save_dir = Path(
                json.loads(
                    self.app_settings_file.read_text())["clipboard_save_dir"])

        self.hostname = socket.gethostname()
        self.clipboard_save_file = self.clipboard_save_dir / f"{self.hostname}.clips.json"

    def read_clips_from_files(self, initialize=False):
        print('running read_clips_from_files')
        update_clips = []
        for json_filepath in self.clipboard_save_dir.glob("*.clips.json"):
            if json_filepath == self.clipboard_save_file and not initialize:
                continue
            with json_filepath.open() as f:
                update_clips += json.load(f)
        for clip in update_clips:
            if clip not in self.clips:
                self.clips.append(clip)
        self.clips_model.setStringList(self.clips)

    def on_clip(self, mode):
        print(f'on_clip mode:{mode}')
        if mode == QClipboard.Mode.Clipboard:
            self.save_clipboard_contents_and_update_gui()

    def update_save_folder(self, new_save_folder):
        new_save_folder_path = Path(new_save_folder)
        if new_save_folder_path.exists():
            self.app_settings_file.write_text(
                json.dumps(dict(clipboard_save_dir=new_save_folder)))
            self.clipboard_save_dir = new_save_folder_path
            self.clipboard_save_file = self.clipboard_save_dir / f"{self.hostname}.clips.json"
            self.clipboard_save_dir_line_widget.setText(new_save_folder)

    def pick_save_folder(self):
        self.update_save_folder(
            QFileDialog.getExistingDirectory(
                self.window, "Pick shared network folder to sync clipboards",
                os.fspath(Path.home()), 0))

    def save_clipboard_contents_and_update_gui(self):
        last_clipboard_contents = self.clipboard.text(
            QClipboard.Mode.Clipboard)
        self.clips.insert(0, last_clipboard_contents)
        self.clips_model.setStringList(self.clips)
        print(f'new clipboard contents: {last_clipboard_contents}')
        self.clipboard_save_dir.mkdir(parents=True, exist_ok=True)
        with open(self.clipboard_save_file, 'w') as f:
            json.dump(self.clips, f)

    def copy_entry(self):
        results = []
        for index in self.clips_view.selectedIndexes():
            results.append(self.clips[index.row()])
        self.clipboard.setText('\n'.join(results))

    def delete_entry(self):
        for index in self.clips_view.selectedIndexes():
            self.clips.pop(index.row())
        self.clips_model.setStringList(self.clips)
        self.clipboard_save_dir.mkdir(parents=True, exist_ok=True)
        with open(self.clipboard_save_file, 'w') as f:
            json.dump(self.clips, f)

    def run(self):
        app = QApplication(sys.argv)
        self.clipboard = app.clipboard()
        self.window = QWidget()
        self.layout = QVBoxLayout()
        self.clipboard_save_dir_line_widget = QLineEdit()
        self.clipboard_save_dir_line_widget.setText(
            os.fspath(self.clipboard_save_dir))
        self.clipboard_save_dir_line_widget.textChanged.connect(
            self.update_save_folder)
        self.launch_file_dialog_button = QPushButton()
        self.launch_file_dialog_button.setIcon(
            self.window.style().standardIcon(
                QtWidgets.QStyle.SP_DialogOpenButton))
        self.launch_file_dialog_button.clicked.connect(self.pick_save_folder)
        self.clips_view = QListView()
        self.clips_model = QStringListModel()
        self.clips_view.setModel(self.clips_model)
        self.read_clips_from_files(initialize=True)
        self.save_folders_label = QLabel("clipboard network saves folder")
        self.layout.addWidget(self.save_folders_label)
        line = QWidget()
        line.setLayout(QHBoxLayout())
        line.layout().addWidget(self.clipboard_save_dir_line_widget)
        line.layout().addWidget(self.launch_file_dialog_button)
        self.layout.addWidget(line)

        self.copy_button = QPushButton()
        self.copy_button.setText("Copy")
        self.copy_button.clicked.connect(self.copy_entry)

        self.delete_button = QPushButton()
        self.delete_button.setText("Delete")
        self.delete_button.clicked.connect(self.delete_entry)

        buttons = QWidget()
        buttons.setLayout(QHBoxLayout())
        buttons.layout().addWidget(self.copy_button)
        buttons.layout().addWidget(self.delete_button)

        self.layout.addWidget(buttons)

        self.layout.addWidget(self.clips_view)
        self.window.setLayout(self.layout)
        self.clipboard.changed.connect(self.on_clip)
        self.timer = QTimer()
        self.timer.timeout.connect(self.read_clips_from_files)
        self.timer.start(5 * 1000)
        self.window.resize(
            QDesktopWidget().availableGeometry(self.window).size() * 0.5)
        self.window.show()
        sys.exit(app.exec_())
예제 #30
0
class filesSelector(QWidget):
    def __init__(self, *args, **kwargs):
        #super(filesSelector, self).__init__(*args, **kwargs)

        #Widget for displaying all the options for adding files to the view
        self.directory_browse = QWidget()
        self.directory_browse_layout = QVBoxLayout()
        self.directory_browse.setLayout(self.directory_browse_layout)

        #List View for displaying the files which have been selected for processing
        self.file_list_view = QListView()
        self.file_list_view.setObjectName("treeView")
        self.directory_browse_layout.addWidget(self.file_list_view)

        #The widget within the Directory_Browse widget which will contain all the options for loading files
        self.file_option_widget = QWidget()
        self.file_option_widget_layout = QHBoxLayout()
        self.file_option_widget.setLayout(self.file_option_widget_layout)
        self.directory_browse_layout.addWidget(self.file_option_widget)

        #The button for browsing to the folder which needs to be added
        self.select_folder_button = QPushButton()
        self.select_folder_button.setObjectName("browseButton")
        self.select_folder_button.setText("Select Folder")
        self.file_option_widget_layout.addWidget(self.select_folder_button)

        #The button for adding selected files from a directory
        self.select_file_button = QPushButton()
        self.select_file_button.setObjectName("browseButton")
        self.select_file_button.setText("Select File")
        self.file_option_widget_layout.addWidget(self.select_file_button)

        #The widget which will contain the list of all the extensions which are to be added
        # self.file_extension_widget = QWidget()
        # self.file_extension_widget.setObjectName("fileExtensionWidget")
        # self.file_extension_widget_layout = QHBoxLayout()
        # self.file_extension_widget.setLayout(self.file_option_widget_layout)
        # self.file_option_widget_layout.addWidget(self.file_extension_widget)

        #What happens when we click the browse directory button?
        self.select_folder_button.clicked.connect(self.select_folder)

        #Custom model to hold the names of the all the files which are selected
        self.file_model = QStandardItemModel()

    def select_folder(self):
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.Directory)
        dialog.setOption(QFileDialog.ShowDirsOnly)

        self.directoryUrl = dialog.getExistingDirectoryUrl()

        self.selected_folder = self.directoryUrl.toDisplayString()[7:]
        self.nameFileArray = [
            f for f in os.listdir(self.selected_folder)
            if os.path.isfile(os.path.join(self.selected_folder, f))
        ]

        # item = QStandardItem("All")
        # item.setCheckState(Qt.Checked)
        # item.setCheckable(True)
        #self.file_model.appendRow(item)

        #self.file_model, self.file_option_listview = self.create_checkBoxes(self.nameFileArray, self.file_model, self.file_option_listview)

        self.file_model = self.create_checkBoxes(self.nameFileArray,
                                                 self.file_model,
                                                 self.file_list_view)
        for name in self.nameFileArray:
            self.file_model.appendRow(
                self.append_checkbox(name, self.file_model, Qt.Checked))
        self.file_list_view.setModel(self.file_model)

        #self.file_model, self.file_option_listview = self.create_checkBoxes(self.nameFileArray, self.file_model, self.file_option_listview)

    def create_checkBoxes(self, array, model, view):
        model.appendRow(self.append_checkbox("All", model, Qt.Checked))
        # for item in array:
        #     model = self.append_checkbox(item, model, Qt.Checked)
        # view.setModel(model)
        return model

    def append_checkbox(self, item, model, checkdStatus):
        item = QStandardItem(item)
        item.setCheckState(checkdStatus)
        item.setCheckable(True)
        #model.appendRow(item)

        return item