def __init__(self, fileBrowser): QComboBox.__init__(self, fileBrowser) self._fileBrowser = fileBrowser self.setAttribute(Qt.WA_MacShowFocusRect, False) self.setAttribute(Qt.WA_MacSmallSize) self.setEditable(True) self.setMinimumContentsLength(1) self.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon) self.lineEdit().setReadOnly(False) self._completionModel = QDirModel(self.lineEdit()) self._completionModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot) self.lineEdit().setCompleter(QCompleter(self._completionModel, self.lineEdit())) # TODO QDirModel is deprecated but QCompleter does not yet handle # QFileSystemModel - please update when possible. self._count = 0 # Show popup action self._showPopupAction = QAction(QIcon(':enkiicons/filtered.png'), "File browser history", self) self._showPopupAction.setShortcut('Ctrl+H') core.actionManager().addAction("mNavigation/mFileBrowser/aMenuShow", self._showPopupAction) self._showPopupAction.triggered.connect(self._onShowPopup) # reconnected in self.updateComboItems() self.currentIndexChanged[int].connect(self._onItemSelected)
def initUI(self): hbox = QHBoxLayout(self) self.lefttopframe = MyPixmap() # self.lefttopframe.frameWidth = 40 self.lefttopframe.setMinimumWidth(150) self.lefttopframe.setFrameShape(QFrame.StyledPanel) # leftbottomframe = QFrame(self) self.dirmodel = QDirModel() qtree = QTreeView() qtree.setMaximumWidth(300) qtree.setModel(self.dirmodel) qtree.setRootIndex( self.dirmodel.index(QDir.currentPath() + '/mapeditor/Maps')) qtree.doubleClicked.connect(self.tree_clicked) # leftbottomframe.setFrameShape(QFrame.StyledPanel) splitter = QSplitter(Qt.Vertical) splitter.handleWidth = 20 splitter.addWidget(self.lefttopframe) splitter.addWidget(qtree) self.rightframe = MyPixmap(self) # rightframe.set_tileset() self.rightframe.setFrameShape(QFrame.StyledPanel) splitter2 = QSplitter(Qt.Horizontal) splitter2.addWidget(splitter) splitter2.addWidget(self.rightframe) hbox.addWidget(splitter2) self.setLayout(hbox)
def __init__(self, mainWindow, parent = None): super().__init__(parent) self.mDirectoryEdit = QLineEdit() self.mMapsView = MapsView(mainWindow) self.setObjectName("MapsDock") widget = QWidget(self) layout = QVBoxLayout(widget) layout.setContentsMargins(5, 5, 5, 5) dirLayout = QHBoxLayout() # QDirModel is obsolete, but I could not get QFileSystemModel to work here model = QDirModel(self) model.setFilter(QDir.AllDirs | QDir.Dirs | QDir.Drives | QDir.NoDotAndDotDot) completer = QCompleter(model, self) self.mDirectoryEdit.setCompleter(completer) button = QPushButton(self.tr("Browse...")) dirLayout.addWidget(self.mDirectoryEdit) dirLayout.addWidget(button) layout.addWidget(self.mMapsView) layout.addLayout(dirLayout) self.setWidget(widget) self.retranslateUi() button.clicked.connect(self.browse) prefs = preferences.Preferences.instance() prefs.mapsDirectoryChanged.connect(self.onMapsDirectoryChanged) self.mDirectoryEdit.setText(prefs.mapsDirectory()) self.mDirectoryEdit.returnPressed.connect(self.editedMapsDirectory)
def __init__(self, parent=None): QWidget.__init__(self, parent) self.setWindowTitle('View') dirModel = QDirModel() lay = QGridLayout(self) lv = QListView() lay.addWidget(lv, 0, 0) lv.setModel(dirModel) lvi = QListView() lay.addWidget(lvi, 0, 1) lvi.setViewMode(QListView.IconMode) lvi.setModel(dirModel) trv = QTreeView() lay.addWidget(trv, 1, 0) trv.setModel(dirModel) tav = QTableView() tav.setModel(dirModel) lay.addWidget(tav, 1, 1) cwdIndex = dirModel.index(QDir.currentPath()) lv.setRootIndex(cwdIndex) lvi.setRootIndex(cwdIndex) trv.setRootIndex(cwdIndex) tav.setRootIndex(cwdIndex)
def __init__(self, parent=None, *args, **kwargs) -> None: super(Demo, self).__init__(parent, *args, **kwargs) expanduser = os.path.expanduser('~') print(expanduser) model = QDirModel() self.setModel(model) self.setRootIndex(model.index(expanduser))
def main(): app = QApplication(sys.argv) model = QDirModel() view = QTreeView() view.setModel(model) home_directory = expanduser("~") view.setRootIndex(model.index(home_directory)) view.show() sys.exit(app.exec_())
class MyCentralWidget(QWidget): def __init__(self, parent=None, flags=Qt.WindowFlags()): super().__init__(parent=parent, flags=flags) self.initUI() self.pix = '' def initUI(self): hbox = QHBoxLayout(self) self.lefttopframe = MyPixmap() # self.lefttopframe.frameWidth = 40 self.lefttopframe.setMinimumWidth(150) self.lefttopframe.setFrameShape(QFrame.StyledPanel) # leftbottomframe = QFrame(self) self.dirmodel = QDirModel() qtree = QTreeView() qtree.setMaximumWidth(300) qtree.setModel(self.dirmodel) qtree.setRootIndex( self.dirmodel.index(QDir.currentPath() + '/mapeditor/Maps')) qtree.doubleClicked.connect(self.tree_clicked) # leftbottomframe.setFrameShape(QFrame.StyledPanel) splitter = QSplitter(Qt.Vertical) splitter.handleWidth = 20 splitter.addWidget(self.lefttopframe) splitter.addWidget(qtree) self.rightframe = MyPixmap(self) # rightframe.set_tileset() self.rightframe.setFrameShape(QFrame.StyledPanel) splitter2 = QSplitter(Qt.Horizontal) splitter2.addWidget(splitter) splitter2.addWidget(self.rightframe) hbox.addWidget(splitter2) self.setLayout(hbox) def tree_clicked(self, idx): print(self.dirmodel.fileName(idx)) self.rightframe.set_tileset(QDir.currentPath() + '/mapeditor/' + self.dirmodel.filePath(idx)) def paintEvent(self, e): painter = QPainter(self) if self.pix != '': painter.drawPixmap(self.lefttopframe.rect(), self.pix) def set_tileset(self, path): # print ('set tileset %s' % path) self.path = path self.pix = QPixmap() self.pix.load(path)
def __init__(self, new_project=True, parent=None): super().__init__(parent) self.ui = Ui_ProjectDialog() self.ui.setupUi(self) self.sample_rate = self.ui.spinBoxSampleRate.value() self.freq = self.ui.spinBoxFreq.value() self.path = self.ui.lineEdit_Path.text() self.new_project = new_project self.commited = False self.setModal(True) completer = QCompleter() completer.setModel(QDirModel(completer)) self.ui.lineEdit_Path.setCompleter(completer) if not self.new_project: self.ui.btnSelectPath.hide() self.ui.lineEdit_Path.setDisabled(True) self.ui.lblNewPath.hide() self.create_connects() self.ui.lineEdit_Path.setText( os.path.realpath(os.path.join(os.curdir, "new"))) self.on_path_edited()
def __init__(self, parent): super(DirectorySelectionWidget, self).__init__('Location of custom DSDL definitions [optional]', parent) self._dir_selection = None dir_textbox = QLineEdit(self) dir_textbox.setText(self._dir_selection) dir_text_completer = QCompleter(self) dir_text_completer.setCaseSensitivity(Qt.CaseSensitive) dir_text_completer.setModel(QDirModel(self)) dir_textbox.setCompleter(dir_text_completer) def on_edit(): self._dir_selection = str(dir_textbox.text()) dir_textbox.textChanged.connect(on_edit) dir_browser = QPushButton('Browse', self) def on_browse(): self._dir_selection = str( QFileDialog.getExistingDirectory(self, 'Select Directory')) dir_textbox.setText(self._dir_selection) dir_browser.clicked.connect(on_browse) layout = QHBoxLayout(self) layout.addWidget(dir_textbox) layout.addWidget(dir_browser) self.setLayout(layout)
def data(self, index, role=Qt.DisplayRole): if (role == Qt.DisplayRole and index.column() == 0): path = QDir.toNativeSeparators(self.filePath(index)) if path.endsWith(QDir.separator()): path.chop(1) return path return QDirModel.data(self, index, role)
def setData(self, index, value, role): if (role == Qt.CheckStateRole and index.column() == 0): self.checks[index] = value self.updateCheckBoxSignal.emit(index, value) return True return QDirModel.setData(self, index, value, role)
def __init__(self, proPath, parent=None): super(MyMainWindow, self).__init__(parent) # self.setCentralWidget(self.widget) self.proPath = proPath #************** 初始化窗口 self.setupUi(self) # 设置窗口的标题 self.setWindowTitle('ftpFilesys') # 设置窗口的图标,引用当前目录下的web.png图片 self.setWindowIcon(QIcon(self.proPath + '/Icon/LOGO.jpg')) self.setSignal() self.downing = True #************** 初始化按键 # self.Bt_down.setEnabled(False) self.Bt_up.setEnabled(False) # 创建SSH对象 self.ssh = paramiko.SSHClient() # 允许连接不在know_hosts文件中的主机,否则可能报错:paramiko.ssh_exception.SSHException: Server '192.168.43.140' not found in known_hosts self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ftp_root = "/home/sd/ftp/biaodingCloud" #************** 初始化变量 """FTP窗口""" self.ftp = myFTP() # 实例化FTP self.ftp.encoding = "utf-8" self.select_file = "" # listView中选择的文件名 self.file_list = [] # 存放查询FTP返回的当前目录所有文件列表 self.ftp_tip = [] #存储当前登陆信息 """本地窗口""" # self.sysfile = QFileSystemModel() # 获取本地文件系统 # self.sysfile.setRootPath('') # self.treeView_local.setModel(self.sysfile) self.model = QDirModel() self.model.setFilter(QtCore.QDir.Dirs | QtCore.QDir.NoDotAndDotDot) self.treeView_local.header().hide() # 隐藏表头 self.treeView_local.setModel(self.model) for col in range(1, 4): self.treeView_local.setColumnHidden(col, True) self.save_path = "" # self.treeView_local.setRootIndex(self.model.index(self.save_path)) self.save_name = "" self.lineEdit_ip.setText("192.168.200.11") self.lineEdit_port.setText("21") self.lineEdit_user.setText("admin") self.lineEdit_pwd.setText("123")
def __init__(self, installed_plugins, highlighted_plugins=None, parent=None): super().__init__(parent) self.backend_handler = BackendHandler() self.ui = Ui_DialogOptions() self.ui.setupUi(self) self.setAttribute(Qt.WA_DeleteOnClose) layout = QHBoxLayout(self.ui.tab_plugins) self.plugin_controller = PluginController(installed_plugins, highlighted_plugins, parent=self) layout.addWidget(self.plugin_controller) self.ui.tab_plugins.setLayout(layout) self.ui.labelWindowsError.setVisible(sys.platform == "win32" and platform.architecture()[0] != "64bit") self.ui.checkBoxAlignLabels.setChecked(constants.SETTINGS.value("align_labels", True, bool)) self.ui.checkBoxFallBackTheme.setChecked(constants.SETTINGS.value('use_fallback_theme', False, bool)) self.ui.checkBoxShowConfirmCloseDialog.setChecked(not constants.SETTINGS.value('not_show_close_dialog', False, bool)) self.ui.checkBoxHoldShiftToDrag.setChecked(constants.SETTINGS.value('hold_shift_to_drag', False, bool)) self.ui.checkBoxDefaultFuzzingPause.setChecked(constants.SETTINGS.value('use_default_fuzzing_pause', True, bool)) self.ui.radioButtonGnuradioDirectory.setChecked(self.backend_handler.use_gnuradio_install_dir) self.ui.radioButtonPython2Interpreter.setChecked(not self.backend_handler.use_gnuradio_install_dir) if self.backend_handler.gnuradio_install_dir: self.ui.lineEditGnuradioDirectory.setText(self.backend_handler.gnuradio_install_dir) if self.backend_handler.python2_exe: self.ui.lineEditPython2Interpreter.setText(self.backend_handler.python2_exe) self.ui.doubleSpinBoxFuzzingPause.setValue(constants.SETTINGS.value("default_fuzzing_pause", 10**6, int)) self.ui.doubleSpinBoxFuzzingPause.setEnabled(constants.SETTINGS.value('use_default_fuzzing_pause', True, bool)) completer = QCompleter() completer.setModel(QDirModel(completer)) self.ui.lineEditPython2Interpreter.setCompleter(completer) self.ui.lineEditGnuradioDirectory.setCompleter(completer) for dev_name in self.backend_handler.DEVICE_NAMES: self.ui.listWidgetDevices.addItem(dev_name) self.set_device_enabled_suffix() self.ui.listWidgetDevices.setCurrentRow(0) self.set_gnuradio_status() self.refresh_device_tab() self.create_connects() self.old_symbol_tresh = 10 self.old_show_pause_as_time = False self.field_type_table_model = FieldTypeTableModel([], parent=self) self.ui.tblLabeltypes.setModel(self.field_type_table_model) self.ui.tblLabeltypes.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.ui.tblLabeltypes.setItemDelegateForColumn(1, ComboBoxDelegate([f.name for f in FieldType.Function], return_index=False, parent=self)) self.ui.tblLabeltypes.setItemDelegateForColumn(2, ComboBoxDelegate(ProtocolLabel.DISPLAY_FORMATS, parent=self)) self.read_options() self.old_default_view = self.ui.comboBoxDefaultView.currentIndex()
def __init__(self, new_project=True, project_manager: ProjectManager = None, parent=None): super().__init__(parent) if not new_project: assert project_manager is not None self.ui = Ui_ProjectDialog() self.ui.setupUi(self) self.setWindowFlags(Qt.Window) if new_project: self.participant_table_model = ParticipantTableModel([]) else: self.participant_table_model = ParticipantTableModel(project_manager.participants) self.ui.spinBoxSampleRate.setValue(project_manager.device_conf["sample_rate"]) self.ui.spinBoxFreq.setValue(project_manager.device_conf["frequency"]) self.ui.spinBoxBandwidth.setValue(project_manager.device_conf["bandwidth"]) self.ui.spinBoxGain.setValue(project_manager.device_conf.get("gain", config.DEFAULT_GAIN)) self.ui.txtEdDescription.setPlainText(project_manager.description) self.ui.lineEdit_Path.setText(project_manager.project_path) self.ui.lineEditBroadcastAddress.setText(project_manager.broadcast_address_hex) self.ui.btnSelectPath.hide() self.ui.lineEdit_Path.setDisabled(True) self.setWindowTitle("Edit project settings") self.ui.lNewProject.setText("Edit project") self.ui.tblParticipants.setModel(self.participant_table_model) self.participant_table_model.update() self.ui.lineEditBroadcastAddress.setValidator(QRegExpValidator(QRegExp("([a-fA-F ]|[0-9]){,}"))) self.sample_rate = self.ui.spinBoxSampleRate.value() self.freq = self.ui.spinBoxFreq.value() self.bandwidth = self.ui.spinBoxBandwidth.value() self.gain = self.ui.spinBoxGain.value() self.description = self.ui.txtEdDescription.toPlainText() self.broadcast_address_hex = self.ui.lineEditBroadcastAddress.text() self.path = self.ui.lineEdit_Path.text() self.new_project = new_project self.committed = False self.setModal(True) completer = QCompleter() completer.setModel(QDirModel(completer)) self.ui.lineEdit_Path.setCompleter(completer) self.create_connects() # add two participants if self.participant_table_model.rowCount() == 0 and new_project: self.ui.btnAddParticipant.click() self.ui.btnAddParticipant.click() if new_project: self.ui.lineEdit_Path.setText(os.path.realpath(os.path.join(os.curdir, "new"))) self.on_line_edit_path_text_edited() self.restoreGeometry(settings.read("{}/geometry".format(self.__class__.__name__), type=bytes))
class Demo(QWidget): def __init__(self): super(Demo, self).__init__() self.resize(600, 300) self.model = QDirModel(self) # 1 self.model.setReadOnly(False) self.model.setSorting(QDir.Name | QDir.IgnoreCase) self.tree = QTreeView(self) # 2 self.tree.setModel(self.model) self.tree.clicked.connect(self.show_info) self.index = self.model.index(QDir.currentPath()) self.tree.expand(self.index) self.tree.scrollTo(self.index) self.info_label = QLabel(self) # 3 self.v_layout = QVBoxLayout() self.v_layout.addWidget(self.tree) self.v_layout.addWidget(self.info_label) self.setLayout(self.v_layout) def show_info(self): # 4 index = self.tree.currentIndex() file_name = self.model.fileName(index) file_path = self.model.filePath(index) file_info = 'File Name: {}\nFile Path: {}'.format(file_name, file_path) self.info_label.setText(file_info)
def __init__(self, freq, samp_rate, bw, gain, device, noise, center, bit_length, tolerance, modulation_type_index, parent=None, testing_mode=False): self.is_rx = True super().__init__(freq, samp_rate, bw, gain, device, parent=parent, testing_mode=testing_mode) self.ui.stackedWidget.setCurrentIndex(2) self.hide_send_ui_items() self.hide_receive_ui_items() self.ui.sliderYscale.hide() self.ui.label_y_scale.hide() self.ui.spinbox_sniff_Noise.setValue(noise) self.ui.spinbox_sniff_Center.setValue(center) self.ui.spinbox_sniff_BitLen.setValue(bit_length) self.ui.spinbox_sniff_ErrorTolerance.setValue(tolerance) self.ui.combox_sniff_Modulation.setCurrentIndex(modulation_type_index) device = self.ui.cbDevice.currentText() self.sniffer = ProtocolSniffer(bit_length, center, noise, tolerance, modulation_type_index, samp_rate, freq, gain, bw, device, testing_mode=testing_mode) self.set_sniff_ui_items_visible(True) self.set_device_ui_items_visible( device != NetworkSDRInterfacePlugin.NETWORK_SDR_NAME) # Auto Complete like a Boss completer = QCompleter() completer.setModel(QDirModel(completer)) self.ui.lineEdit_sniff_OutputFile.setCompleter(completer) self.create_connects()
def __init__(self, device_name: str, project_manager: ProjectManager, signal=None, backend_handler=None, network_raw_mode=False, signals=None, parent=None): super().__init__(parent) self.ui = Ui_SniffSettings() self.ui.setupUi(self) signals = signals if signals is not None else [] self.project_manager = project_manager for encoding in self.project_manager.decodings: self.ui.comboBox_sniff_encoding.addItem(encoding.name) self.bootstrap(project_manager.device_conf, signal, enforce_default=True) self.sniffer = ProtocolSniffer( bit_len=self.ui.spinbox_sniff_BitLen.value(), center=self.ui.spinbox_sniff_Center.value(), noise=self.ui.spinbox_sniff_Noise.value(), tolerance=self.ui.spinbox_sniff_ErrorTolerance.value(), modulation_type=self.ui.combox_sniff_Modulation.currentIndex(), device=device_name, backend_handler=BackendHandler() if backend_handler is None else backend_handler, network_raw_mode=network_raw_mode) self.sniffer.adaptive_noise = self.ui.checkBoxAdaptiveNoise.isChecked() self.sniffer.automatic_center = self.ui.checkBoxAutoCenter.isChecked() self.create_connects() self.ui.comboBox_sniff_encoding.currentIndexChanged.emit( self.ui.comboBox_sniff_encoding.currentIndex()) self.ui.comboBox_sniff_viewtype.setCurrentIndex( constants.SETTINGS.value('default_view', 0, int)) # Auto Complete like a Boss completer = QCompleter() completer.setModel(QDirModel(completer)) self.ui.lineEdit_sniff_OutputFile.setCompleter(completer) self.signals = signals if len(signals) == 0: self.ui.label_sniff_Signal.hide() self.ui.btn_sniff_use_signal.hide() self.ui.comboBox_sniff_signal.hide() else: for signal in signals: self.ui.comboBox_sniff_signal.addItem(signal.name)
def __init__(self, *args, **kwargs): super(DirLineEdit, self).__init__(*args, **kwargs) completer = QCompleter() completer.setCompletionMode(QCompleter.PopupCompletion) dirfilter = QDir.AllEntries | QDir.NoDotAndDotDot | QDir.Hidden sortflags = QDir.DirsFirst | QDir.IgnoreCase dirmodel = QDirModel(['*'], dirfilter, sortflags, completer) completer.setModel(dirmodel) self.setCompleter(completer)
def __init__(self, parent, node, node_monitor): super(DynamicNodeIDAllocatorWidget, self).__init__(parent) self.setTitle( 'Dynamic node ID allocation server (uavcan.protocol.dynamic_node_id.*)' ) self._node = node self._node_monitor = node_monitor self._allocator = None self._allocation_table = BasicTable(self, self.COLUMNS, font=get_monospace_font()) self._allocation_table_update_timer = QTimer(self) self._allocation_table_update_timer.setSingleShot(False) self._allocation_table_update_timer.start(500) self._allocation_table_update_timer.timeout.connect(self._update_table) self._start_stop_button = make_icon_button( 'rocket', 'Launch/stop the dynamic node ID allocation server', self, checkable=True) self._start_stop_button.clicked.connect(self._on_start_stop_button) self._database_file = CommitableComboBoxWithHistory(self) self._database_file.setAcceptDrops(True) self._database_file.setToolTip('Path to the allocation table file') self._database_file.setCurrentText(self.DEFAULT_DATABASE_FILE) self._database_file.addItem(self._database_file.currentText()) self._database_file.on_commit = self._on_start_stop_button self._select_database_file = make_icon_button( 'folder-open-o', 'Open allocation table file', self, on_clicked=self._on_select_database_file) db_file_completer = QCompleter() db_file_completer.setModel(QDirModel(db_file_completer)) self._database_file.setCompleter(db_file_completer) self._sync_gui() layout = QVBoxLayout(self) controls_layout = QHBoxLayout(self) controls_layout.addWidget(self._start_stop_button) controls_layout.addWidget(self._database_file, 1) controls_layout.addWidget(self._select_database_file) layout.addLayout(controls_layout) layout.addWidget(self._allocation_table, 1) self.setLayout(layout)
def show_dir(self): model = QDirModel() model.setFilter(QDir.AllDirs | QDir.Files | QDir.NoDotAndDotDot) model.setNameFilters(["*.pickle", '*.pickle.gz']) _dir = self.lineEdit.text() if not _dir: _dir = '.' self.treeView.setModel(model) self.treeView.setRootIndex(model.index(_dir))
def __init__(self): super(Demo, self).__init__() self.resize(600, 300) self.model = QDirModel(self) # 1 self.model.setReadOnly(False) self.model.setSorting(QDir.Name | QDir.IgnoreCase) self.tree = QTreeView(self) # 2 self.tree.setModel(self.model) self.tree.clicked.connect(self.show_info) self.index = self.model.index(QDir.currentPath()) self.tree.expand(self.index) self.tree.scrollTo(self.index) self.info_label = QLabel(self) # 3 self.v_layout = QVBoxLayout() self.v_layout.addWidget(self.tree) self.v_layout.addWidget(self.info_label) self.setLayout(self.v_layout)
def __init__(self): super(Mapp, self).__init__() self.dir = QDirModel(self) self.tree = QTreeView(self) self.tree.setModel(self.dir) w, h = 800, 600 r = 30 self.tree.setFixedSize(w - r, h - r) self.tree.move(10, 10) self.setFixedSize(w, h) self.tree.clicked.connect(self.montre)
def __init__(self, freq, samp_rate, bw, gain, device, noise, center, bit_length, tolerance, modulation_type_index, parent=None): super().__init__(parent) self.ui = Ui_SniffProtocol() self.ui.setupUi(self) self.setAttribute(Qt.WA_DeleteOnClose) self.ui.spinBoxFreq.setValue(freq) self.ui.spinBoxSampleRate.setValue(samp_rate) self.ui.spinBoxBandwidth.setValue(bw) self.ui.spinBoxGain.setValue(gain) self.ui.spinboxNoise.setValue(noise) self.ui.spinboxCenter.setValue(center) self.ui.spinboxBitLen.setValue(bit_length) self.ui.spinboxErrorTolerance.setValue(tolerance) self.ui.comboxModulation.setCurrentIndex(modulation_type_index) self.sniffer = ProtocolSniffer(bit_length, center, noise, tolerance, modulation_type_index, samp_rate, freq, gain, bw, device) self.sniffer.usrp_ip = self.ui.lineEditIP.text() self.ui.btnStop.setEnabled(False) self.ui.btnClear.setEnabled(False) self.ui.cbDevice.clear() items = [] if constants.SETTINGS.value('usrp_available', type=bool): items.append("USRP") if constants.SETTINGS.value('hackrf_available', type=bool): items.append("HackRF") self.ui.cbDevice.addItems(items) if device in items: self.ui.cbDevice.setCurrentIndex(items.index(device)) self.on_device_edited() ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])" ipRegex = QRegExp("^" + ipRange + "\\." + ipRange + "\\." + ipRange + "\\." + ipRange + "$") self.ui.lineEditIP.setValidator(QRegExpValidator(ipRegex)) # Auto Complete like a Boss completer = QCompleter() completer.setModel(QDirModel(completer)) self.ui.lineEditOutputFile.setCompleter(completer) self.create_connects()
def initUI(self): dm = QDirModel() treeview = QTreeView(self) treeview.setModel(dm) vbox = QVBoxLayout() vbox.addWidget(treeview) self.setLayout(vbox) self.resize(640, 480) self.setWindowTitle('TreeView') self.show()
def __init__(self, parent=None): super().__init__(parent) completer = QCompleter() completer.setModel(QDirModel(completer)) self.line_edit_external_program = QLineEdit() self.line_edit_external_program.setCompleter(completer) self.line_edit_external_program.setPlaceholderText( "Type in a path to external program.") self.layout = QHBoxLayout() self.layout.setContentsMargins(0, 0, 0, 0) self.layout.setSpacing(0) self.layout.addWidget(self.line_edit_external_program) self.setLayout(self.layout)
def __init__(self, device_name: str, project_manager: ProjectManager, signal=None, backend_handler=None, network_raw_mode=False, real_time=False, parent=None): super().__init__(parent) self.ui = Ui_SniffSettings() self.ui.setupUi(self) conf = project_manager.device_conf bit_length = conf.get("bit_len", signal.bit_len if signal else 100) modulation_type_index = conf.get("modulation_index", signal.modulation_type if signal else 1) tolerance = conf.get("tolerance", signal.tolerance if signal else 5) noise = conf.get("noise", signal.noise_threshold if signal else 0.001) center = conf.get("center", signal.qad_center if signal else 0.02) decoding_name = conf.get("decoding_name", "") self.sniffer = ProtocolSniffer(bit_len=bit_length, center=center, noise=noise, tolerance=tolerance, modulation_type=modulation_type_index, device=device_name, backend_handler=BackendHandler() if backend_handler is None else backend_handler, network_raw_mode=network_raw_mode, real_time=real_time) self.ui.spinbox_sniff_Noise.setValue(noise) self.ui.spinbox_sniff_Center.setValue(center) self.ui.spinbox_sniff_BitLen.setValue(bit_length) self.ui.spinbox_sniff_ErrorTolerance.setValue(tolerance) self.ui.combox_sniff_Modulation.setCurrentIndex(modulation_type_index) self.project_manager = project_manager for encoding in self.project_manager.decodings: self.ui.comboBox_sniff_encoding.addItem(encoding.name) self.create_connects() if decoding_name: self.ui.comboBox_sniff_encoding.setCurrentText(decoding_name) self.ui.comboBox_sniff_viewtype.setCurrentIndex(constants.SETTINGS.value('default_view', 0, int)) # Auto Complete like a Boss completer = QCompleter() completer.setModel(QDirModel(completer)) self.ui.lineEdit_sniff_OutputFile.setCompleter(completer)
def __init__(self): super(Demo, self).__init__() self.dir_model = QDirModel(self) # 2 self.list_view = QListView(self) # 3 self.tree_view = QTreeView(self) self.table_view = QTableView(self) self.list_view.setModel(self.dir_model) self.tree_view.setModel(self.dir_model) self.table_view.setModel(self.dir_model) self.tree_view.doubleClicked.connect(self.show_func) # 4 # self.setOrientation(Qt.Vertical) # 5 self.addWidget(self.list_view) self.addWidget(self.tree_view) self.insertWidget(0, self.table_view) self.setSizes([300, 200, 200]) print(self.count())
def __init__(self, filename="", parent=None): super().__init__(parent) self.ui = Ui_DialogCSVImport() self.ui.setupUi(self) self.setAttribute(Qt.WA_DeleteOnClose) self.ui.btnAutoDefault.hide() completer = QCompleter() completer.setModel(QDirModel(completer)) self.ui.lineEditFilename.setCompleter(completer) self.filename = None # type: str self.ui.lineEditFilename.setText(filename) self.update_file() self.ui.tableWidgetPreview.setColumnHidden(self.COLUMNS["T"], True) self.update_preview() self.create_connects()
def __init__(self, parent): super(ManualInstallWidget, self).__init__() self._parent = parent vbox = QVBoxLayout(self) form = QFormLayout() self._txtName = QLineEdit() self._txtName.setPlaceholderText('my_plugin') self._txtVersion = QLineEdit() self._txtVersion.setPlaceholderText('0.1') form.addRow(translations.TR_PROJECT_NAME, self._txtName) form.addRow(translations.TR_VERSION, self._txtVersion) vbox.addLayout(form) hPath = QHBoxLayout() self._txtFilePath = QLineEdit() self._txtFilePath.setPlaceholderText( os.path.join(os.path.expanduser('~'), 'full', 'path', 'to', 'plugin.zip')) self._btnFilePath = QPushButton(QIcon(":img/open"), '') self.completer, self.dirs = QCompleter(self), QDirModel(self) self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot) self.completer.setModel(self.dirs) self._txtFilePath.setCompleter(self.completer) hPath.addWidget(QLabel(translations.TR_FILENAME)) hPath.addWidget(self._txtFilePath) hPath.addWidget(self._btnFilePath) vbox.addLayout(hPath) vbox.addSpacerItem( QSpacerItem(0, 1, QSizePolicy.Expanding, QSizePolicy.Expanding)) hbox = QHBoxLayout() hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) self._btnInstall = QPushButton(translations.TR_INSTALL) hbox.addWidget(self._btnInstall) vbox.addLayout(hbox) #Signals self._btnFilePath.clicked['bool'].connect(self._load_plugin_path) self._btnInstall.clicked['bool'].connect(self.install_plugin)
def __init__(self, parent, default=None): super(PathItem, self).__init__(parent) self.on_remove = lambda _: None self.on_path_changed = lambda *_: None self._remove_button = make_icon_button('remove', 'Remove this path', self, on_clicked=lambda: self.on_remove(self)) completer = QCompleter(self) completer.setModel(QDirModel(completer)) self._path_bar = CommitableComboBoxWithHistory(self) if default: self._path_bar.setCurrentText(default) self._path_bar.setCompleter(completer) self._path_bar.setAcceptDrops(True) self._path_bar.setToolTip('Lookup path for file services; should point either to a file or to a directory') self._path_bar.currentTextChanged.connect(self._on_path_changed) self._select_file_button = make_icon_button('file-o', 'Specify file path', self, on_clicked=self._on_select_path_file) self._select_dir_button = make_icon_button('folder-open-o', 'Specify directory path', self, on_clicked=self._on_select_path_directory) self._hit_count_label = LabelWithIcon(get_icon('upload'), '0', self) self._hit_count_label.setToolTip('Hit count') layout = QHBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self._remove_button) layout.addWidget(self._path_bar, 1) layout.addWidget(self._select_file_button) layout.addWidget(self._select_dir_button) layout.addWidget(self._hit_count_label) self.setLayout(layout)
class ComboBox(QComboBox): """File browser combo box. Widget and functionality """ def __init__(self, fileBrowser): QComboBox.__init__(self, fileBrowser) self._fileBrowser = fileBrowser self.setAttribute(Qt.WA_MacShowFocusRect, False) self.setAttribute(Qt.WA_MacSmallSize) self.setEditable(True) self.setMinimumContentsLength(1) self.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon) self.lineEdit().setReadOnly(False) self._completionModel = QDirModel(self.lineEdit()) self._completionModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot) self.lineEdit().setCompleter(QCompleter(self._completionModel, self.lineEdit())) # TODO QDirModel is deprecated but QCompleter does not yet handle # QFileSystemModel - please update when possible. self._count = 0 # Show popup action self._showPopupAction = QAction(QIcon(':enkiicons/filtered.png'), "File browser history", self) self._showPopupAction.setShortcut('Ctrl+H') core.actionManager().addAction("mNavigation/mFileBrowser/aMenuShow", self._showPopupAction) self._showPopupAction.triggered.connect(self._onShowPopup) # reconnected in self.updateComboItems() self.currentIndexChanged[int].connect(self._onItemSelected) def terminate(self): """Explicitly called destructor """ core.actionManager().removeAction(self._showPopupAction) def _onShowPopup(self, triggered): """Handler for self._showPopupAction """ self._fileBrowser.show() self.showPopup() def _onItemSelected(self, index): """Handler of item selection in the combo box """ if self.count() > self._count: # It is user input path = self.itemText(index) if os.path.isdir(path): self._fileBrowser.setCurrentPath(path) else: path = self.itemData(index) self._fileBrowser.setCurrentPath(path) def updateItems(self, items): """Update items in the combo box according to current history """ self.currentIndexChanged[int].disconnect() self.clear() # Current text self.addItem(os.path.normpath(self._fileBrowser.currentPath())) self.setItemData(0, self._fileBrowser.currentPath()) self.insertSeparator(self.count()) for index, path in enumerate(items): self.addItem(os.path.normpath(path)) self.setItemData(index + 2, path) self._count = self.count() self.currentIndexChanged[int].connect(self._onItemSelected)
class SearchWidget(QFrame): """Widget, appeared, when Ctrl+F pressed. Has different forms for different search modes """ Normal = 'normal' Good = 'good' Bad = 'bad' Incorrect = 'incorrect' visibilityChanged = pyqtSignal(bool) """ visibilityChanged(visible) **Signal** emitted, when widget has been shown or hidden """ # pylint: disable=W0105 searchInDirectoryStartPressed = pyqtSignal(type(re.compile('')), list, str) """ searchInDirectoryStartPressed(regEx, mask, path) **Signal** emitted, when 'search in directory' button had been pressed """ # pylint: disable=W0105 searchInDirectoryStopPressed = pyqtSignal() """ searchInDirectoryStopPressed() **Signal** emitted, when 'stop search in directory' button had been pressed """ # pylint: disable=W0105 replaceCheckedStartPressed = pyqtSignal(str) """ replaceCheckedStartPressed(replText) **Signal** emitted, when 'replace checked' button had been pressed """ # pylint: disable=W0105 replaceCheckedStopPressed = pyqtSignal() """ replaceCheckedStartPressed() **Signal** emitted, when 'stop replacing checked' button had been pressed """ # pylint: disable=W0105 searchRegExpChanged = pyqtSignal(type(re.compile(''))) """ searchRegExpValidStateChanged(regEx) **Signal** emitted, when search regexp has been changed. If reg exp is invalid - regEx object contains empty pattern """ # pylint: disable=W0105 searchNext = pyqtSignal() """ searchNext() **Signal** emitted, when 'Search Next' had been pressed """ # pylint: disable=W0105 searchPrevious = pyqtSignal() """ searchPrevious() **Signal** emitted, when 'Search Previous' had been pressed """ # pylint: disable=W0105 replaceFileOne = pyqtSignal(str) """ replaceFileOne(replText) **Signal** emitted, when 'Replace' had been pressed """ # pylint: disable=W0105 replaceFileAll = pyqtSignal(str) """ replaceFileAll(replText) **Signal** emitted, when 'Replace All' had been pressed """ # pylint: disable=W0105 def __init__(self, plugin): QFrame.__init__(self, core.workspace()) self._mode = None self.plugin = plugin uic.loadUi(os.path.join(os.path.dirname(__file__), 'SearchWidget.ui'), self) self.cbSearch.setCompleter(None) self.cbReplace.setCompleter(None) self.cbMask.setCompleter(None) self.fsModel = QDirModel(self.cbPath.lineEdit()) self.fsModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot) self.cbPath.lineEdit().setCompleter(QCompleter(self.fsModel, self.cbPath.lineEdit())) self._pathBackspaceShortcut = QShortcut(QKeySequence("Ctrl+Backspace"), self.cbPath, self._onPathBackspace) self._pathBackspaceShortcut.setContext(Qt.WidgetWithChildrenShortcut) # TODO QDirModel is deprecated but QCompleter does not yet handle # QFileSystemodel - please update when possible.""" self.cbSearch.setCompleter(None) self.pbSearchStop.setVisible(False) self.pbReplaceCheckedStop.setVisible(False) self._progress = QProgressBar(self) self._progress.setAlignment(Qt.AlignCenter) self._progress.setToolTip(self.tr("Search in progress...")) self._progress.setMaximumSize(QSize(80, 16)) core.mainWindow().statusBar().insertPermanentWidget(1, self._progress) self._progress.setVisible(False) # cd up action self.tbCdUp = QToolButton(self.cbPath.lineEdit()) self.tbCdUp.setIcon(QIcon(":/enkiicons/go-up.png")) self.tbCdUp.setCursor(Qt.ArrowCursor) self.tbCdUp.installEventFilter(self) # for drawing button self.cbSearch.installEventFilter(self) # for catching Tab and Shift+Tab self.cbReplace.installEventFilter(self) # for catching Tab and Shift+Tab self.cbPath.installEventFilter(self) # for catching Tab and Shift+Tab self.cbMask.installEventFilter(self) # for catching Tab and Shift+Tab self._closeShortcut = QShortcut(QKeySequence("Esc"), self) self._closeShortcut.setContext(Qt.WidgetWithChildrenShortcut) self._closeShortcut.activated.connect(self.hide) # connections self.cbSearch.lineEdit().textChanged.connect(self._onSearchRegExpChanged) self.cbSearch.lineEdit().returnPressed.connect(self._onReturnPressed) self.cbReplace.lineEdit().returnPressed.connect(self._onReturnPressed) self.cbPath.lineEdit().returnPressed.connect(self._onReturnPressed) self.cbMask.lineEdit().returnPressed.connect(self._onReturnPressed) self.cbRegularExpression.stateChanged.connect(self._onSearchRegExpChanged) self.cbCaseSensitive.stateChanged.connect(self._onSearchRegExpChanged) self.cbWholeWord.stateChanged.connect(self._onSearchRegExpChanged) self.tbCdUp.clicked.connect(self._onCdUpPressed) self.pbNext.pressed.connect(self.searchNext) self.pbPrevious.pressed.connect(self.searchPrevious) self.pbSearchStop.pressed.connect(self.searchInDirectoryStopPressed) self.pbReplaceCheckedStop.pressed.connect(self.replaceCheckedStopPressed) core.mainWindow().hideAllWindows.connect(self.hide) core.workspace().escPressed.connect(self.hide) core.workspace().currentDocumentChanged.connect( lambda old, new: self.setVisible(self.isVisible() and new is not None)) def show(self): """Reimplemented function. Sends signal """ super(SearchWidget, self).show() self.visibilityChanged.emit(self.isVisible()) def hide(self): """Reimplemented function. Sends signal, returns focus to workspace """ super(SearchWidget, self).hide() core.workspace().focusCurrentDocument() self.visibilityChanged.emit(self.isVisible()) def setVisible(self, visible): """Reimplemented function. Sends signal """ super(SearchWidget, self).setVisible(visible) self.visibilityChanged.emit(self.isVisible()) def _regExEscape(self, text): """Improved version of re.escape() Doesn't escape space, comma, underscore. Escapes \n and \t """ text = re.escape(text) # re.escape escapes space, comma, underscore, but, it is not necessary and makes text not readable for symbol in (' ,_=\'"/:@#%&'): text = text.replace('\\' + symbol, symbol) text = text.replace('\\\n', '\\n') text = text.replace('\\\t', '\\t') return text def _makeEscapeSeqsVisible(self, text): """Replace invisible \n and \t with escape sequences """ text = text.replace('\\', '\\\\') text = text.replace('\t', '\\t') text = text.replace('\n', '\\n') return text def setMode(self, mode): """Change search mode. i.e. from "Search file" to "Replace directory" """ if self._mode == mode and self.isVisible(): if core.workspace().currentDocument() is not None and \ not core.workspace().currentDocument().hasFocus(): self.cbSearch.lineEdit().selectAll() self.cbSearch.setFocus() self._mode = mode # Set Search and Replace text document = core.workspace().currentDocument() if document is not None and \ document.hasFocus() and \ document.qutepart.selectedText: searchText = document.qutepart.selectedText self.cbReplace.setEditText(self._makeEscapeSeqsVisible(searchText)) if self.cbRegularExpression.checkState() == Qt.Checked: searchText = self._regExEscape(searchText) self.cbSearch.setEditText(searchText) if not self.cbReplace.lineEdit().text() and \ self.cbSearch.lineEdit().text() and \ not self.cbRegularExpression.checkState() == Qt.Checked: replaceText = self.cbSearch.lineEdit().text().replace('\\', '\\\\') self.cbReplace.setEditText(replaceText) # Move focus to Search edit self.cbSearch.setFocus() self.cbSearch.lineEdit().selectAll() # Set search path if mode & MODE_FLAG_DIRECTORY and \ not (self.isVisible() and self.cbPath.isVisible()): try: searchPath = os.path.abspath(str(os.path.curdir)) except OSError: # current directory might have been deleted pass else: self.cbPath.setEditText(searchPath) # Set widgets visibility flag according to state widgets = (self.wSearch, self.pbPrevious, self.pbNext, self.pbSearch, self.wReplace, self.wPath, self.pbReplace, self.pbReplaceAll, self.pbReplaceChecked, self.wOptions, self.wMask) # wSear pbPrev pbNext pbSear wRepl wPath pbRep pbRAll pbRCHK wOpti wMask visible = \ {MODE_SEARCH: (1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0,), MODE_REPLACE: (1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0,), MODE_SEARCH_DIRECTORY: (1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1,), MODE_REPLACE_DIRECTORY: (1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1,), MODE_SEARCH_OPENED_FILES: (1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1,), MODE_REPLACE_OPENED_FILES: (1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1,)} for i, widget in enumerate(widgets): widget.setVisible(visible[mode][i]) # Search next button text if mode == MODE_REPLACE: self.pbNext.setText('Next') else: self.pbNext.setText('Next↵') # Finaly show all with valid size self.show() # show before updating widgets and labels self._updateLabels() self._updateWidgets() def eventFilter(self, object_, event): """ Event filter for mode switch tool button Draws icons in the search and path lineEdits """ if event.type() == QEvent.Paint and object_ is self.tbCdUp: # draw CdUp button in search path QLineEdit toolButton = object_ lineEdit = self.cbPath.lineEdit() lineEdit.setContentsMargins(lineEdit.height(), 0, 0, 0) height = lineEdit.height() availableRect = QRect(0, 0, height, height) if toolButton.rect() != availableRect: toolButton.setGeometry(availableRect) painter = QPainter(toolButton) toolButton.icon().paint(painter, availableRect) return True elif event.type() == QEvent.KeyPress: # Tab and Shift+Tab in QLineEdits if event.key() == Qt.Key_Tab: self._moveFocus(1) return True elif event.key() == Qt.Key_Backtab: self._moveFocus(-1) return True return QFrame.eventFilter(self, object_, event) def _onReturnPressed(self): """Return or Enter pressed on widget. Search next or Replace next """ if self.pbReplace.isVisible(): self.pbReplace.click() elif self.pbNext.isVisible(): self.pbNext.click() elif self.pbSearch.isVisible(): self.pbSearch.click() elif self.pbSearchStop.isVisible(): self.pbSearchStop.click() def _onPathBackspace(self): """Ctrl+Backspace pressed on path. Remove 1 path level. Default behavior would be to remove one word on Linux or all on Windows """ path = self.cbPath.currentText() if path.endswith('/') or \ path.endswith('\\'): path = path[:-1] head, tail = os.path.split(path) if head and \ head != path: if not head.endswith(os.sep): head += os.sep self.cbPath.lineEdit().setText(head) def _moveFocus(self, step): """Move focus forward or backward according to step. Standard Qt Keyboard focus algorithm doesn't allow circular navigation """ allFocusableWidgets = (self.cbSearch, self.cbReplace, self.cbPath, self.cbMask) visibleWidgets = [widget for widget in allFocusableWidgets if widget.isVisible()] try: focusedIndex = visibleWidgets.index(QApplication.focusWidget()) except ValueError: print('Invalid focused widget in Search Widget', file=sys.stderr) return nextFocusedIndex = (focusedIndex + step) % len(visibleWidgets) visibleWidgets[nextFocusedIndex].setFocus() visibleWidgets[nextFocusedIndex].lineEdit().selectAll() def _updateLabels(self): """Update 'Search' 'Replace' 'Path' labels geometry """ width = 0 if self.lSearch.isVisible(): width = max(width, self.lSearch.minimumSizeHint().width()) if self.lReplace.isVisible(): width = max(width, self.lReplace.minimumSizeHint().width()) if self.lPath.isVisible(): width = max(width, self.lPath.minimumSizeHint().width()) self.lSearch.setMinimumWidth(width) self.lReplace.setMinimumWidth(width) self.lPath.setMinimumWidth(width) def _updateWidgets(self): """Update geometry of widgets with buttons """ width = 0 if self.wSearchRight.isVisible(): width = max(width, self.wSearchRight.minimumSizeHint().width()) if self.wReplaceRight.isVisible(): width = max(width, self.wReplaceRight.minimumSizeHint().width()) if self.wPathRight.isVisible(): width = max(width, self.wPathRight.minimumSizeHint().width()) self.wSearchRight.setMinimumWidth(width) self.wReplaceRight.setMinimumWidth(width) self.wPathRight.setMinimumWidth(width) def updateComboBoxes(self): """Update comboboxes with last used texts """ searchText = self.cbSearch.currentText() replaceText = self.cbReplace.currentText() maskText = self.cbMask.currentText() # search if searchText: index = self.cbSearch.findText(searchText) if index == -1: self.cbSearch.addItem(searchText) # replace if replaceText: index = self.cbReplace.findText(replaceText) if index == -1: self.cbReplace.addItem(replaceText) # mask if maskText: index = self.cbMask.findText(maskText) if index == -1: self.cbMask.addItem(maskText) def _searchPatternTextAndFlags(self): """Get search pattern and flags """ pattern = self.cbSearch.currentText() pattern = pattern.replace('\u2029', '\n') # replace unicode paragraph separator with habitual \n if not self.cbRegularExpression.checkState() == Qt.Checked: pattern = re.escape(pattern) if self.cbWholeWord.checkState() == Qt.Checked: pattern = r'\b' + pattern + r'\b' flags = 0 if not self.cbCaseSensitive.checkState() == Qt.Checked: flags = re.IGNORECASE return pattern, flags def getRegExp(self): """Read search parameters from controls and present it as a regular expression """ pattern, flags = self._searchPatternTextAndFlags() return re.compile(pattern, flags) def isSearchRegExpValid(self): """Try to compile search pattern to check if it is valid Returns bool result and text error """ pattern, flags = self._searchPatternTextAndFlags() try: re.compile(pattern, flags) except re.error as ex: return False, str(ex) return True, None def _getSearchMask(self): """Get search mask as list of patterns """ mask = [s.strip() for s in self.cbMask.currentText().split(' ')] # remove empty mask = [_f for _f in mask if _f] return mask def setState(self, state): """Change line edit color according to search result """ widget = self.cbSearch.lineEdit() color = {SearchWidget.Normal: QApplication.instance().palette().color(QPalette.Base), SearchWidget.Good: QColor(Qt.green), SearchWidget.Bad: QColor(Qt.red), SearchWidget.Incorrect: QColor(Qt.darkYellow)} stateColor = color[state] if state != SearchWidget.Normal: stateColor.setAlpha(100) pal = widget.palette() pal.setColor(widget.backgroundRole(), stateColor) widget.setPalette(pal) def setSearchInProgress(self, inProgress): """Search thread started or stopped """ self.pbSearchStop.setVisible(inProgress) self.pbSearch.setVisible(not inProgress) self._updateWidgets() self._progress.setVisible(inProgress) def onSearchProgressChanged(self, value, total): """Signal from the thread, progress changed """ self._progress.setValue(value) self._progress.setMaximum(total) def setReplaceInProgress(self, inProgress): """Replace thread started or stopped """ self.pbReplaceCheckedStop.setVisible(inProgress) self.pbReplaceChecked.setVisible(not inProgress) self._updateWidgets() def setSearchInFileActionsEnabled(self, enabled): """Set enabled state for Next, Prev, Replace, ReplaceAll """ for button in (self.pbNext, self.pbPrevious, self.pbReplace, self.pbReplaceAll): button.setEnabled(enabled) def _onSearchRegExpChanged(self): """User edited search text or checked/unchecked checkboxes """ valid, error = self.isSearchRegExpValid() if valid: self.setState(self.Normal) core.mainWindow().statusBar().clearMessage() self.pbSearch.setEnabled(len(self.getRegExp().pattern) > 0) else: core.mainWindow().statusBar().showMessage(error, 3000) self.setState(self.Incorrect) self.pbSearch.setEnabled(False) self.searchRegExpChanged.emit(re.compile('')) return self.searchRegExpChanged.emit(self.getRegExp()) def _onCdUpPressed(self): """User pressed "Up" button, need to remove one level from search path """ text = self.cbPath.currentText() if not os.path.exists(text): return editText = os.path.normpath(os.path.join(text, os.path.pardir)) self.cbPath.setEditText(editText) def on_pbSearch_pressed(self): """Handler of click on "Search" button (for search in directory) """ self.setState(SearchWidget.Normal) self.searchInDirectoryStartPressed.emit(self.getRegExp(), self._getSearchMask(), self.cbPath.currentText()) def on_pbReplace_pressed(self): """Handler of click on "Replace" (in file) button """ self.replaceFileOne.emit(self.cbReplace.currentText()) def on_pbReplaceAll_pressed(self): """Handler of click on "Replace all" (in file) button """ self.replaceFileAll.emit(self.cbReplace.currentText()) def on_pbReplaceChecked_pressed(self): """Handler of click on "Replace checked" (in directory) button """ self.replaceCheckedStartPressed.emit(self.cbReplace.currentText()) def on_pbBrowse_pressed(self): """Handler of click on "Browse" button. Explores FS for search directory path """ path = QFileDialog.getExistingDirectory(self, self.tr("Search path"), self.cbPath.currentText()) if path: self.cbPath.setEditText(path)
def __init__(self, plugin): QFrame.__init__(self, core.workspace()) self._mode = None self.plugin = plugin uic.loadUi(os.path.join(os.path.dirname(__file__), 'SearchWidget.ui'), self) self.cbSearch.setCompleter(None) self.cbReplace.setCompleter(None) self.cbMask.setCompleter(None) self.fsModel = QDirModel(self.cbPath.lineEdit()) self.fsModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot) self.cbPath.lineEdit().setCompleter(QCompleter(self.fsModel, self.cbPath.lineEdit())) self._pathBackspaceShortcut = QShortcut(QKeySequence("Ctrl+Backspace"), self.cbPath, self._onPathBackspace) self._pathBackspaceShortcut.setContext(Qt.WidgetWithChildrenShortcut) # TODO QDirModel is deprecated but QCompleter does not yet handle # QFileSystemodel - please update when possible.""" self.cbSearch.setCompleter(None) self.pbSearchStop.setVisible(False) self.pbReplaceCheckedStop.setVisible(False) self._progress = QProgressBar(self) self._progress.setAlignment(Qt.AlignCenter) self._progress.setToolTip(self.tr("Search in progress...")) self._progress.setMaximumSize(QSize(80, 16)) core.mainWindow().statusBar().insertPermanentWidget(1, self._progress) self._progress.setVisible(False) # cd up action self.tbCdUp = QToolButton(self.cbPath.lineEdit()) self.tbCdUp.setIcon(QIcon(":/enkiicons/go-up.png")) self.tbCdUp.setCursor(Qt.ArrowCursor) self.tbCdUp.installEventFilter(self) # for drawing button self.cbSearch.installEventFilter(self) # for catching Tab and Shift+Tab self.cbReplace.installEventFilter(self) # for catching Tab and Shift+Tab self.cbPath.installEventFilter(self) # for catching Tab and Shift+Tab self.cbMask.installEventFilter(self) # for catching Tab and Shift+Tab self._closeShortcut = QShortcut(QKeySequence("Esc"), self) self._closeShortcut.setContext(Qt.WidgetWithChildrenShortcut) self._closeShortcut.activated.connect(self.hide) # connections self.cbSearch.lineEdit().textChanged.connect(self._onSearchRegExpChanged) self.cbSearch.lineEdit().returnPressed.connect(self._onReturnPressed) self.cbReplace.lineEdit().returnPressed.connect(self._onReturnPressed) self.cbPath.lineEdit().returnPressed.connect(self._onReturnPressed) self.cbMask.lineEdit().returnPressed.connect(self._onReturnPressed) self.cbRegularExpression.stateChanged.connect(self._onSearchRegExpChanged) self.cbCaseSensitive.stateChanged.connect(self._onSearchRegExpChanged) self.cbWholeWord.stateChanged.connect(self._onSearchRegExpChanged) self.tbCdUp.clicked.connect(self._onCdUpPressed) self.pbNext.pressed.connect(self.searchNext) self.pbPrevious.pressed.connect(self.searchPrevious) self.pbSearchStop.pressed.connect(self.searchInDirectoryStopPressed) self.pbReplaceCheckedStop.pressed.connect(self.replaceCheckedStopPressed) core.mainWindow().hideAllWindows.connect(self.hide) core.workspace().escPressed.connect(self.hide) core.workspace().currentDocumentChanged.connect( lambda old, new: self.setVisible(self.isVisible() and new is not None))
def __init__(self,parent=None): QWidget.__init__(self,parent) self.setWindowTitle('View') dirModel=QDirModel() lay=QGridLayout(self) lv=QListView() lay.addWidget(lv,0,0) lv.setModel(dirModel) lvi=QListView() lay.addWidget(lvi,0,1) lvi.setViewMode(QListView.IconMode) lvi.setModel(dirModel) trv=QTreeView() lay.addWidget(trv,1,0) trv.setModel(dirModel) tav=QTableView() tav.setModel(dirModel) lay.addWidget(tav,1,1) cwdIndex=dirModel.index(QDir.currentPath()) lv.setRootIndex(cwdIndex) lvi.setRootIndex(cwdIndex) trv.setRootIndex(cwdIndex) tav.setRootIndex(cwdIndex)