def view(self): """create view and import layers""" layer = QgsMapLayerRegistry.instance().mapLayer( self.current_layers[0] ) uri = QgsDataSourceURI(layer.source()) mtch = re.match(r'(.+)_([^_]+)_rev_(head|\d+)', uri.schema()) schema = mtch.group(1) assert(schema) dlg = QDialog() layout = QVBoxLayout(dlg) button_box = QDialogButtonBox(dlg) button_box.setStandardButtons( QDialogButtonBox.Cancel|QDialogButtonBox.Ok) button_box.accepted.connect(dlg.accept) button_box.rejected.connect(dlg.reject) pcur = versioning_base.Db( psycopg2.connect(self.pg_conn_info()) ) pcur.execute("SELECT rev, commit_msg, branch, date, author " "FROM "+schema+".revisions") revs = pcur.fetchall() pcur.close() tblw = QTableWidget( dlg ) tblw.setRowCount(len(revs)) tblw.setColumnCount(5) tblw.setSortingEnabled(True) tblw.setHorizontalHeaderLabels(['Revision', 'Commit Message', 'Branch', 'Date', 'Author']) tblw.verticalHeader().setVisible(False) for i, rev in enumerate(revs): for j, item in enumerate(rev): tblw.setItem(i, j, QTableWidgetItem( str(item) )) layout.addWidget( tblw ) layout.addWidget( button_box ) dlg.resize( 600, 300 ) if not dlg.exec_() : return rows = set() for i in tblw.selectedIndexes(): rows.add(i.row()) for row in rows: branch = revs[row][2] rev = revs[row][0] versioning_base.add_revision_view(uri.connectionInfo(), schema, branch, rev ) grp_name = branch+' revision '+str(rev) grp_idx = self.iface.legendInterface().addGroup( grp_name ) for layer_id in reversed(self.current_layers): layer = QgsMapLayerRegistry.instance().mapLayer(layer_id) new_uri = QgsDataSourceURI(layer.source()) new_uri.setDataSource(schema+'_'+branch+'_rev_'+str(rev), new_uri.table(), new_uri.geometryColumn(), new_uri.sql(), new_uri.keyColumn()) display_name = QgsMapLayerRegistry.instance().mapLayer(layer_id).name() src = new_uri.uri().replace('()','') new_layer = self.iface.addVectorLayer( src, display_name, 'postgres') self.iface.legendInterface().moveLayer( new_layer, grp_idx)
def add_new_table(self, rel, name): import itertools table = QTableWidget() table.setRowCount(0) table.setColumnCount(0) data = itertools.chain([rel.fields], rel.content) for row_data in data: row = table.rowCount() table.setColumnCount(len(row_data)) for col, text in enumerate(row_data): item = QTableWidgetItem() item.setText(text) if row == 0: table.setHorizontalHeaderItem(col, item) else: table.setItem(row - 1, col, item) table.insertRow(row) table.removeRow(table.rowCount() - 1) self.stacked.addWidget(table) self.stacked.setCurrentIndex(self.stacked.count() - 1) lateral = Pireal.get_service("lateral") lateral.add_item_list([name])
def iconChooser(self): ' Choose a Icon and copy it to clipboard ' # from .std_icon_naming import std_icon_naming as a # prv = QDialog(self.dock) prv.setWindowFlags(Qt.FramelessWindowHint) prv.setAutoFillBackground(True) prv.setGeometry(self.fileView.geometry()) table = QTableWidget(prv) table.setColumnCount(1) table.setRowCount(len(a)) table.verticalHeader().setVisible(True) table.horizontalHeader().setVisible(False) table.setShowGrid(True) table.setIconSize(QSize(128, 128)) for index, icon in enumerate(a): item = QTableWidgetItem(QIcon.fromTheme(icon), '') # item.setData(Qt.UserRole, '') item.setToolTip(icon) table.setItem(index, 0, item) table.clicked.connect(lambda: QApplication.clipboard().setText( 'QtGui.QIcon.fromTheme("{}")'.format(table.currentItem().toolTip()))) table.doubleClicked.connect(prv.close) table.resizeColumnsToContents() table.resizeRowsToContents() QLabel('<h3> <br> 1 Click Copy, 2 Clicks Close </h3>', table) table.resize(prv.size()) prv.exec_()
def view(self): """create view and import layers""" layer = QgsMapLayerRegistry.instance().mapLayer(self.current_layers[0]) uri = QgsDataSourceURI(layer.source()) mtch = re.match(r'(.+)_([^_]+)_rev_(head|\d+)', uri.schema()) schema = mtch.group(1) assert (schema) dlg = QDialog() layout = QVBoxLayout(dlg) button_box = QDialogButtonBox(dlg) button_box.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) button_box.accepted.connect(dlg.accept) button_box.rejected.connect(dlg.reject) pcur = versioning_base.Db(psycopg2.connect(self.pg_conn_info())) pcur.execute("SELECT rev, commit_msg, branch, date, author " "FROM " + schema + ".revisions") revs = pcur.fetchall() pcur.close() tblw = QTableWidget(dlg) tblw.setRowCount(len(revs)) tblw.setColumnCount(5) tblw.setSortingEnabled(True) tblw.setHorizontalHeaderLabels( ['Revision', 'Commit Message', 'Branch', 'Date', 'Author']) tblw.verticalHeader().setVisible(False) for i, rev in enumerate(revs): for j, item in enumerate(rev): tblw.setItem(i, j, QTableWidgetItem(str(item))) layout.addWidget(tblw) layout.addWidget(button_box) dlg.resize(600, 300) if not dlg.exec_(): return rows = set() for i in tblw.selectedIndexes(): rows.add(i.row()) for row in rows: branch = revs[row][2] rev = revs[row][0] versioning_base.add_revision_view(uri.connectionInfo(), schema, branch, rev) grp_name = branch + ' revision ' + str(rev) grp_idx = self.iface.legendInterface().addGroup(grp_name) for layer_id in reversed(self.current_layers): layer = QgsMapLayerRegistry.instance().mapLayer(layer_id) new_uri = QgsDataSourceURI(layer.source()) new_uri.setDataSource( schema + '_' + branch + '_rev_' + str(rev), new_uri.table(), new_uri.geometryColumn(), new_uri.sql(), new_uri.keyColumn()) display_name = QgsMapLayerRegistry.instance().mapLayer( layer_id).name() src = new_uri.uri().replace('()', '') new_layer = self.iface.addVectorLayer(src, display_name, 'postgres') self.iface.legendInterface().moveLayer(new_layer, grp_idx)
class Widget(QWidget): def __init__(self, parent=None): super(Widget, self).__init__(parent) self.tableWidget = QTableWidget() self.tableWidget.setColumnCount(3) self.tableWidget.verticalHeader().hide() groupBox1 = QGroupBox('Experiment data') buttonHelp = QPushButton('help') buttonHelp.setEnabled(False) buttonHelp.setToolTip('Enter the input weights into the "w(i)" column and the signal values into the "x(i)"\n' + 'column.\n\n' + 'TIP: To recalculate the result, press Enter. To increment and decrement the value\n' + 'using the arrow keys, press F2 first or click the apropriate table cell with the left\n' + 'mouse button.') hboxLayoutGroupBox1 = QHBoxLayout() hboxLayoutGroupBox1.addWidget(QLabel('Enter the input weights and signal\n' + 'values in the table below')) hboxLayoutGroupBox1.addWidget(buttonHelp) vboxLayoutGroupBox1 = QVBoxLayout() vboxLayoutGroupBox1.addLayout(hboxLayoutGroupBox1) vboxLayoutGroupBox1.addWidget(self.tableWidget) groupBox1.setLayout(vboxLayoutGroupBox1) vboxLayout1 = QVBoxLayout() vboxLayout1.addWidget(QLabel('Perform experiments')) vboxLayout1.addWidget(groupBox1) groupBox2 = QGroupBox('Experiment result') self.memoryEdit = QLineEdit() self.memoryEdit.setReadOnly(True) self.signalEdit = QLineEdit() self.signalEdit.setReadOnly(True) self.outputEdit = QLineEdit() self.outputEdit.setReadOnly(True) self.buttonRecalculate = QPushButton('Recalculate!') gridLayoutGroupBox2 = QGridLayout() gridLayoutGroupBox2.addWidget(QLabel('Memory trace strength'), 0, 0) gridLayoutGroupBox2.addWidget(self.memoryEdit, 0, 1) gridLayoutGroupBox2.addWidget(QLabel('Input signal strength'), 1, 0) gridLayoutGroupBox2.addWidget(self.signalEdit, 1, 1) gridLayoutGroupBox2.addWidget(QLabel('Output'), 2, 0) gridLayoutGroupBox2.addWidget(self.outputEdit, 2, 1) gridLayoutGroupBox2.addWidget(self.buttonRecalculate, 3, 0) groupBox2.setLayout(gridLayoutGroupBox2) hboxLayout = QHBoxLayout() hboxLayout.addLayout(vboxLayout1) hboxLayout.addWidget(groupBox2) self.setLayout(hboxLayout)
class WellLogEditDialog(QDialog): def __init__(self, current_well_name, current_log_name): super(WellLogEditDialog, self).__init__() self.well = ppp.Well( str(CONF.well_dir / ".{}".format(current_well_name))) self.current_log_name = current_log_name self.well_log = self.well.get_log(current_log_name) self.resize(300, 400) self.initUI() self.button_box.accepted.connect(self.save_edit) self.button_box.rejected.connect(self.close) def initUI(self): self.setWindowIcon(QIcon(':/icon/edit_icon')) self.setWindowTitle("Edit Log {}".format(self.current_log_name)) self.layout = QGridLayout(self) # add a QTableWidget self.tableWidget = QTableWidget(self) self.tableWidget.setColumnCount(2) self.tableWidget.setRowCount(0) self.tableWidget.setHorizontalHeaderItem(0, QTableWidgetItem("Depth")) self.tableWidget.setHorizontalHeaderItem(1, QTableWidgetItem("Data")) n = len(self.well_log.depth) self.tableWidget.setRowCount(n) for i, (de, da) in enumerate(zip(self.well_log.depth, self.well_log.data)): self.tableWidget.setItem(i, 0, QTableWidgetItem(str(de))) self.tableWidget.setItem(i, 1, QTableWidgetItem(str(da))) self.layout.addWidget(self.tableWidget) # add QDialogButtonBox self.button_box = QDialogButtonBox(self) self.button_box.setStandardButtons(QDialogButtonBox.Save | QDialogButtonBox.Cancel) self.layout.addWidget(self.button_box) def save_edit(self): depth_tb = [float(self.tableWidget.item(irow, 0).text()) \ for irow in range(self.tableWidget.rowCount())] data_tb = [float(self.tableWidget.item(irow, 1).text()) \ for irow in range(self.tableWidget.rowCount())] temp_log = ppp.Log() temp_log.depth = depth_tb temp_log.data = data_tb if temp_log != self.well_log: reply = QMessageBox.question( self, "Save", "Log Data has been edited,\nAre you willing to save changes?", QMessageBox.Yes, QMessageBox.Cancel) if reply == QMessageBox.Yes: self.well.update_log(self.current_log_name, temp_log) self.well.save_well() self.close()
def __init__(self, layer, parent=None): super(LayerColortableDialog, self).__init__(parent=parent) h = QHBoxLayout(self) t = QTableWidget(self) t.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) t.setRowCount(len(layer._colorTable)) t.setColumnCount(1) t.setVerticalHeaderLabels(["%d" %i for i in range(len(layer._colorTable))]) for i in range(len(layer._colorTable)): item = QTableWidgetItem(" ") t.setItem(i,0, item); item.setBackgroundColor(QColor.fromRgba(layer._colorTable[i])) item.setFlags(Qt.ItemIsSelectable) h.addWidget(t)
def load_relation(self, filenames=[]): """ Load relation from file """ import csv from PyQt4.QtGui import QTableWidgetItem, QTableWidget from src.core import relation if not filenames: native_dialog = QFileDialog.DontUseNativeDialog directory = os.path.expanduser("~") ffilter = settings.RFILES.split(';;')[-1] filenames = QFileDialog.getOpenFileNames(self, self.tr("Abrir Archivo"), directory, ffilter, native_dialog) if not filenames: return lateral = Pireal.get_service("lateral") for filename in filenames: rel = relation.Relation(filename) relation_name = os.path.splitext(os.path.basename(filename))[0] self.table_widget.relations[relation_name] = rel table = QTableWidget() with open(filename, newline='') as f: table.setRowCount(0) table.setColumnCount(0) csv_reader = csv.reader(f) for row_data in csv_reader: row = table.rowCount() table.setColumnCount(len(row_data)) for column, data in enumerate(row_data): item = QTableWidgetItem() item.setText(data) if row == 0: table.setHorizontalHeaderItem(column, item) else: table.setItem(row - 1, column, item) table.insertRow(row) table.removeRow(table.rowCount() - 1) self.table_widget.stacked.addWidget(table) #FIXME: names names = [os.path.splitext(os.path.basename(i))[0] for i in filenames] lateral.add_item_list(names) lateral.show()
def add_table(self, rows, columns, name, data): table = QTableWidget() table.setRowCount(rows) table.setColumnCount(columns) for k, v in list(data.items()): item = QTableWidgetItem() item.setText(v) if k[0] == 0: table.setHorizontalHeaderItem(k[1], item) else: table.setItem(k[0] - 1, k[1], item) #ntuples = " [ " + str(rows) + " ]" #item_list = QListWidgetItem(name + ntuples) #item_list.setTextAlignment(Qt.AlignHCenter) #self._list_tables.addItem(item_list) self.stacked.addWidget(table) self.stacked.setCurrentIndex(self.stacked.count() - 1)
def addWidgets(self): layout = QVBoxLayout() self.setLayout(layout) preamble = QLabel(self) layout.addWidget(preamble) self.preamble = preamble layout.addSpacing(10) table = QTableWidget(self) layout.addWidget(table) table.setShowGrid(False) table.setSelectionBehavior(QTableWidget.SelectRows) table.setSelectionMode(QTableWidget.SingleSelection) table.setMinimumWidth(400) table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) table.setColumnCount(4) table.hideColumn(0) table.setHorizontalHeaderLabels( ['ID', 'Vault', '# of Items', '# of Peers']) table.setFocusPolicy(Qt.NoFocus) table.itemSelectionChanged.connect(self.rowSelected) hhead = table.horizontalHeader() hhead.setResizeMode(QHeaderView.Stretch) hhead.setHighlightSections(False) vhead = table.verticalHeader() vhead.hide() self.table = table hbox = QHBoxLayout() layout.addLayout(hbox) button = QPushButton('Create Vault', self) button.clicked.connect(self.createVault) hbox.addWidget(button) button = QPushButton('Connect to Vault', self) backend = QApplication.instance().backend() available = backend.locator_is_available() if available: button.clicked.connect(self.connectVault) else: button.setEnabled(False) hbox.addWidget(button) removebtn = QPushButton('Remove Vault', self) removebtn.setEnabled(False) removebtn.clicked.connect(self.removeVault) self.removebtn = removebtn hbox.addWidget(removebtn)
def addWidgets(self): layout = QVBoxLayout() self.setLayout(layout) preamble = QLabel(self) layout.addWidget(preamble) self.preamble = preamble layout.addSpacing(10) table = QTableWidget(self) layout.addWidget(table) table.setShowGrid(False) table.setSelectionBehavior(QTableWidget.SelectRows) table.setSelectionMode(QTableWidget.SingleSelection) table.setMinimumWidth(400) table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) table.setColumnCount(4) table.hideColumn(0) table.setHorizontalHeaderLabels(['ID', 'Vault', '# of Items', '# of Peers']) table.setFocusPolicy(Qt.NoFocus) table.itemSelectionChanged.connect(self.rowSelected) hhead = table.horizontalHeader() hhead.setResizeMode(QHeaderView.Stretch) hhead.setHighlightSections(False) vhead = table.verticalHeader() vhead.hide() self.table = table hbox = QHBoxLayout() layout.addLayout(hbox) button = QPushButton('Create Vault', self) button.clicked.connect(self.createVault) hbox.addWidget(button) button = QPushButton('Connect to Vault', self) backend = QApplication.instance().backend() available = backend.locator_is_available() if available: button.clicked.connect(self.connectVault) else: button.setEnabled(False) hbox.addWidget(button) removebtn = QPushButton('Remove Vault', self) removebtn.setEnabled(False) removebtn.clicked.connect(self.removeVault) self.removebtn = removebtn hbox.addWidget(removebtn)
def create_table(base, items): table = QTableWidget() table_item = QTableWidgetItem() table.setWindowTitle("Liquids Base") table.resize(400, 250) r_count = len(items) c_count = 5 table.setRowCount(r_count) table.setColumnCount(c_count) row = 0 column = 0 for title in items: item = base.get_item(title) table.setItem(row, 0, QTableWidgetItem(item['producer'])) table.setItem(row, 1, QTableWidgetItem(item['title'])) table.setItem(row, 2, QTableWidgetItem(item['price'])) table.setItem(row, 3, QTableWidgetItem(item['rating'])) table.setItem(row, 4, QTableWidgetItem(item['description'])) row += 1 return table
def __init__(self, parent=None, vertical_header=list(), horizontal_header=list(), data=list()): super(Table, self).__init__(parent) layout = QHBoxLayout() resultTable = QTableWidget() resultTable.setRowCount(len(vertical_header)) resultTable.setColumnCount(len(horizontal_header)) resultTable.setHorizontalHeaderLabels(horizontal_header) resultTable.setVerticalHeaderLabels(vertical_header) resultTable.horizontalHeader().setResizeMode(1) resultTable.verticalHeader().setResizeMode(1) resultTable.setEditTriggers(QAbstractItemView.NoEditTriggers) for x, row in enumerate(data): for y, item in enumerate(row): resultTable.setItem(x, y, QTableWidgetItem(str(item))) self.table = resultTable layout.addWidget(self.table) self.setLayout(layout) self.setMinimumWidth(min(len(horizontal_header) * 250, 800)) self.setMinimumHeight(min(len(vertical_header) * 70, 800)) self.setWindowTitle("Report result")
class SimpleListDlg(QDialog): def __init__(self, parent = None, datalist = None, mode='r'): super(SimpleListDlg, self).__init__(parent) self.tbl = QTableWidget() self.mode = mode # read only or write 'r'/'w' self.values = [] if datalist is not None: data = datalist.toList() self.tbl.setRowCount(len(data)) self.tbl.setColumnCount(1) for i,val in enumerate(data): #print i, val.toFloat() self.values.append(val.toFloat()[0]) it = QTableWidgetItem("%g" % val.toFloat()[0]) if self.mode == 'r': it.setFlags(it.flags() & ~Qt.ItemIsEditable) self.tbl.setItem(i,0,it) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok| QDialogButtonBox.Cancel) layout = QVBoxLayout() layout.addWidget(self.tbl) layout.addWidget(buttonBox) self.setLayout(layout) self.connect(buttonBox, SIGNAL("accepted()"), self.accept) self.connect(buttonBox, SIGNAL("rejected()"), self.reject) def accept(self): self.values = [] for i in range(self.tbl.rowCount()): v = self.tbl.item(i,0).data(Qt.EditRole).toFloat() if self.mode == 'w': self.values.append(v[0]) self.done(0) def reject(self): self.values = [] self.done(0)
def build_preview(self): data = self.t.light_parser(self.node) self.layout.addWidget(QLabel("File name : " + data['File'])) tmp_widget = QWidget() tmp_layout = QHBoxLayout(tmp_widget) tmp_layout.addWidget(QLabel("Oldest chunk : " + data['Oldest'])) tmp_layout.addWidget(QLabel("Current chunk : " + data['Current'])) tmp_layout.addWidget(QLabel("Next record : " + data['Next'])) tmp_layout.addWidget( QLabel("Version : " + data['Maj'] + "." + data['Min'])) tmp_layout.addWidget(QLabel("Chunk number : " + data['chunk_nb'])) self.layout.addWidget(tmp_widget) data_list = QTableWidget() data_list.setColumnCount(4) data_list.setHorizontalHeaderLabels( ['Chunk number', 'First record', 'Last record', 'Offset']) data_list.horizontalHeader().setStretchLastSection(True) data_list.verticalHeader().hide() data_list.setSortingEnabled(False) data_list.setSelectionBehavior(QAbstractItemView.SelectRows) data_list.setEditTriggers(QAbstractItemView.NoEditTriggers) data_list.setRowCount(int(data['chunk_nb'])) for chunk_count in range(int(data['chunk_nb'])): rec = data[str(chunk_count)] data_list.setItem(chunk_count, 0, QTableWidgetItem(str(chunk_count))) data_list.setItem(chunk_count, 1, QTableWidgetItem(rec[0])) data_list.setItem(chunk_count, 2, QTableWidgetItem(rec[1])) data_list.setItem(chunk_count, 3, QTableWidgetItem(rec[2])) self.layout.addWidget(data_list)
def addWidgets(self): layout = QVBoxLayout() self.setLayout(layout) preamble = QLabel(self) preamble.setWordWrap(True) layout.addWidget(preamble) self.preamble = preamble layout.addSpacing(10) table = QTableWidget(self) layout.addWidget(table) table.setShowGrid(False) table.setSelectionBehavior(QTableWidget.SelectRows) table.setSelectionMode(QTableWidget.SingleSelection) table.setMinimumWidth(400) table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) table.setColumnCount(4) table.hideColumn(0) table.setHorizontalHeaderLabels(['ID', 'Vault', 'Source', 'On Node']) table.setFocusPolicy(Qt.NoFocus) table.itemSelectionChanged.connect(self.rowSelected) hhead = table.horizontalHeader() hhead.setResizeMode(QHeaderView.Stretch) hhead.setHighlightSections(False) vhead = table.verticalHeader() vhead.hide() self.table = table hbox = QHBoxLayout() layout.addLayout(hbox) cancelbtn = QPushButton('Cancel', self) cancelbtn.clicked.connect(self.vaultmgr.hide) hbox.addWidget(cancelbtn) self.cancelbtn = cancelbtn connectbtn = QPushButton('Connect', self) connectbtn.setEnabled(False) connectbtn.clicked.connect(self.connectVault) hbox.addWidget(connectbtn) self.connectbtn = connectbtn hbox.addStretch(100)
def addWidgets(self): layout = QVBoxLayout() self.setLayout(layout) preamble = QLabel(self) preamble.setWordWrap(True) layout.addWidget(preamble) self.preamble = preamble layout.addSpacing(10) table = QTableWidget(self) layout.addWidget(table) table.setShowGrid(False) table.setSelectionBehavior(QTableWidget.SelectRows) table.setSelectionMode(QTableWidget.SingleSelection) table.setMinimumWidth(400) table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) table.setColumnCount(4) table.hideColumn(0) table.setHorizontalHeaderLabels(['ID', 'Vault', 'Source', 'On Node']) table.setFocusPolicy(Qt.NoFocus) table.itemSelectionChanged.connect(self.rowSelected) hhead = table.horizontalHeader() hhead.setResizeMode(QHeaderView.Stretch) hhead.setHighlightSections(False) vhead = table.verticalHeader(); vhead.hide() self.table = table hbox = QHBoxLayout() layout.addLayout(hbox) cancelbtn = QPushButton('Cancel', self) cancelbtn.clicked.connect(self.vaultmgr.hide) hbox.addWidget(cancelbtn) self.cancelbtn = cancelbtn connectbtn = QPushButton('Connect', self) connectbtn.setEnabled(False) connectbtn.clicked.connect(self.connectVault) hbox.addWidget(connectbtn) self.connectbtn = connectbtn hbox.addStretch(100)
class GUI(object): def __init__(self, MainWindow): MainWindow.setObjectName("MainWindow") # Set size of window MainWindow.resize(800, 589) MainWindow.setFocusPolicy(QtCore.Qt.NoFocus) MainWindow.setWindowTitle("Text to Kill") self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QGridLayout(self.centralwidget) self.gridLayout.setMargin(0) self.gridLayout.setObjectName("gridLayout") self.stackedWidget = QStackedWidget(self.centralwidget) self.stackedWidget.setEnabled(True) self.stackedWidget.setObjectName("stackedWidget") font = QFont() font.setFamily("Times New Roman") # Main menu page self.menuPage = QWidget() self.menuPage.setObjectName("menuPage") self.titleLabel = QLabel(self.menuPage) self.titleLabel.setGeometry(QtCore.QRect(250, 60, 300, 50)) font.setPointSize(45) self.titleLabel.setFont(font) self.titleLabel.setAlignment(QtCore.Qt.AlignCenter) self.titleLabel.setObjectName("titleLabel") self.titleLabel.setText("Text to Kill") self.subtitleLabel = QLabel(self.menuPage) self.subtitleLabel.setGeometry(QtCore.QRect(100, 140, 600, 40)) font.setPointSize(25) self.subtitleLabel.setFont(font) self.subtitleLabel.setAlignment(QtCore.Qt.AlignCenter) self.subtitleLabel.setObjectName("subtitleLabel") self.subtitleLabel.setText("The Murder Mystery Automation System") self.createButton = QPushButton(self.menuPage) self.createButton.setGeometry(QtCore.QRect(310, 260, 180, 60)) self.createButton.setObjectName("createButton") self.createButton.setText("Create Game") self.runButton = QPushButton(self.menuPage) self.runButton.setGeometry(QtCore.QRect(310, 350, 180, 60)) self.runButton.setObjectName("runButton") self.runButton.setText("Run Game") self.stackedWidget.addWidget(self.menuPage) # Create page self.createPage = QWidget() self.createPage.setObjectName("createPage") self.createTabWidget = QTabWidget(self.createPage) self.createTabWidget.setGeometry(QtCore.QRect(0, 0, 800, 600)) self.createTabWidget.setFocusPolicy(QtCore.Qt.NoFocus) self.createTabWidget.setObjectName("createTabWidget") # Create game tab self.createTab = QWidget() self.createTab.setObjectName("createTab") self.createDoneButton = QPushButton(self.createTab) self.createDoneButton.setGeometry(QtCore.QRect(580, 470, 180, 60)) self.createDoneButton.setObjectName("createDoneButton") self.createDoneButton.setText("Done") self.gameNameEdit = QLineEdit(self.createTab) self.gameNameEdit.setGeometry(QtCore.QRect(140, 20, 160, 30)) self.gameNameEdit.setObjectName("gameNameEdit") self.gameNameLabel = QLabel(self.createTab) self.gameNameLabel.setGeometry(QtCore.QRect(20, 25, 110, 20)) font.setPointSize(15) self.gameNameLabel.setFont(font) self.gameNameLabel.setAlignment(QtCore.Qt.AlignCenter) self.gameNameLabel.setObjectName("gameNameLabel") self.gameNameLabel.setText("Game name") self.line = QFrame(self.createTab) self.line.setGeometry(QtCore.QRect(20, 150, 311, 20)) self.line.setFrameShape(QFrame.HLine) self.line.setFrameShadow(QFrame.Sunken) self.line.setObjectName("line") self.addCharLabel = QLabel(self.createTab) self.addCharLabel.setGeometry(QtCore.QRect(20, 180, 160, 20)) font.setPointSize(20) self.addCharLabel.setFont(font) self.addCharLabel.setAlignment(QtCore.Qt.AlignCenter) self.addCharLabel.setObjectName("addCharLabel") self.addCharLabel.setText("Add Character") self.charNameLabel = QLabel(self.createTab) self.charNameLabel.setGeometry(QtCore.QRect(20, 230, 66, 20)) font.setPointSize(15) self.charNameLabel.setFont(font) self.charNameLabel.setAlignment(QtCore.Qt.AlignCenter) self.charNameLabel.setObjectName("charNameLabel") self.charNameLabel.setText("Name") self.charNameEdit = QLineEdit(self.createTab) self.charNameEdit.setGeometry(QtCore.QRect(140, 220, 160, 30)) self.charNameEdit.setObjectName("charNameEdit") self.charAbilScroll = QListWidget(self.createTab) self.charAbilScroll.setGeometry(QtCore.QRect(140, 260, 161, 51)) self.charAbilScroll.setObjectName("charAbilScroll") self.characterTable = QTableWidget(self.createTab) self.characterTable.setGeometry(QtCore.QRect(405, 20, 381, 401)) self.characterTable.setFocusPolicy(QtCore.Qt.NoFocus) self.characterTable.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.characterTable.setRowCount(1) self.characterTable.setColumnCount(2) self.characterTable.setObjectName("characterTable") self.characterTable.horizontalHeader().setVisible(False) self.characterTable.horizontalHeader().setCascadingSectionResizes(False) self.characterTable.horizontalHeader().setMinimumSectionSize(50) self.characterTable.horizontalHeader().setStretchLastSection(True) self.characterTable.verticalHeader().setVisible(False) self.characterTable.verticalHeader().setDefaultSectionSize(30) self.scrollArea = QListWidget(self.createTab) self.scrollArea.setGeometry(QtCore.QRect(140, 60, 161, 71)) self.scrollArea.setObjectName("scrollArea") self.scrollArea.setSelectionMode(3) self.createSaveButton = QPushButton(self.createTab) self.createSaveButton.setGeometry(QtCore.QRect(380, 470, 180, 60)) self.createSaveButton.setObjectName("createSaveButton") self.createSaveButton.setText("Save") self.charAbilitiesLabel = QLabel(self.createTab) self.charAbilitiesLabel.setGeometry(QtCore.QRect(30, 280, 71, 20)) font.setPointSize(15) self.charAbilitiesLabel.setFont(font) self.charAbilitiesLabel.setObjectName("charAbilitiesLabel") self.charAbilitiesLabel.setText("Abilities") self.abilitiesDropdown = QComboBox(self.createTab) self.abilitiesDropdown.setGeometry(QtCore.QRect(140, 330, 151, 25)) self.abilitiesDropdown.setObjectName("abilitiesDropdown") self.addCharButton = QPushButton(self.createTab) self.addCharButton.setGeometry(QtCore.QRect(30, 370, 98, 27)) self.addCharButton.setObjectName("addCharButton") self.addCharButton.setText("Add") self.gameAbilitiesLabel = QLabel(self.createTab) self.gameAbilitiesLabel.setGeometry(QtCore.QRect(30, 80, 71, 20)) self.setGameAbilButton = QPushButton(self.createTab) self.setGameAbilButton.setGeometry(QtCore.QRect(30, 110, 71, 27)) self.setGameAbilButton.setObjectName("setGameAbilButton") self.setGameAbilButton.setText("Set") self.saveCharButton = QPushButton(self.createTab) self.saveCharButton.setGeometry(QtCore.QRect(70, 430, 180, 60)) self.saveCharButton.setObjectName("saveCharButton") self.saveCharButton.setText("Save Character") font.setPointSize(15) self.gameAbilitiesLabel.setFont(font) self.gameAbilitiesLabel.setObjectName("gameAbilitiesLabel") self.gameAbilitiesLabel.setText("Abilities") self.createTabWidget.addTab(self.createTab, "") # Setup tab widget self.setupTab = QWidget() self.setupTab.setObjectName("setupTab") self.setupDoneButton = QPushButton(self.setupTab) self.setupDoneButton.setGeometry(QtCore.QRect(580, 470, 180, 60)) self.setupDoneButton.setObjectName("setupDoneButton") self.setupDoneButton.setText("Done") self.setupTable = QTableWidget(self.setupTab) self.setupTable.setGeometry(QtCore.QRect(20, 20, 750, 400)) self.setupTable.setFocusPolicy(QtCore.Qt.TabFocus) self.setupTable.setRowCount(1) self.setupTable.setColumnCount(3) self.setupTable.setObjectName("setupTable") self.setupTable.horizontalHeader().setVisible(False) self.setupTable.horizontalHeader().setCascadingSectionResizes(False) self.setupTable.horizontalHeader().setDefaultSectionSize(187) self.setupTable.horizontalHeader().setHighlightSections(False) self.setupTable.horizontalHeader().setStretchLastSection(True) self.setupTable.verticalHeader().setVisible(False) self.setupTable.verticalHeader().setHighlightSections(False) self.setupSaveButton = QPushButton(self.setupTab) self.setupSaveButton.setGeometry(QtCore.QRect(380, 470, 180, 60)) self.setupSaveButton.setObjectName("setupSaveButton") self.setupSaveButton.setText("Save") self.createTabWidget.addTab(self.setupTab, "") self.createTabWidget.setTabText(self.createTabWidget.indexOf(self.createTab), "Create New Game") self.createTabWidget.setTabText(self.createTabWidget.indexOf(self.setupTab), "Set Up Game") self.stackedWidget.addWidget(self.createPage) # Game page self.gamePage = QWidget() self.gamePage.setObjectName("gamePage") self.gameTabWidget = QTabWidget(self.gamePage) self.gameTabWidget.setGeometry(QtCore.QRect(0, 0, 800, 600)) self.gameTabWidget.setFocusPolicy(QtCore.Qt.NoFocus) self.gameTabWidget.setObjectName("gameTabWidget") self.statusTab = QWidget() self.statusTab.setObjectName("statusTab") self.startGameButton = QPushButton(self.statusTab) self.startGameButton.setGeometry(QtCore.QRect(60, 180, 180, 60)) self.startGameButton.setObjectName("startGameButton") self.startGameButton.setText("Start Game") self.endGameButton = QPushButton(self.statusTab) self.endGameButton.setGeometry(QtCore.QRect(60, 260, 180, 60)) self.endGameButton.setObjectName("endGameButton") self.endGameButton.setText("End Game") self.loadGameLabel = QLabel(self.statusTab) self.loadGameLabel.setGeometry(QtCore.QRect(20, 65, 101, 21)) font.setPointSize(15) self.loadGameLabel.setFont(font) self.loadGameLabel.setObjectName("loadGameLabel") self.loadGameLabel.setText("Load Game") self.gameTabWidget.addTab(self.statusTab, "") self.logTab = QWidget() self.logTab.setObjectName("logTab") self.logList = QListWidget(self.logTab) self.logList.setGeometry(QtCore.QRect(30, 30, 730, 500)) self.logList.setObjectName("logList") self.gameTabWidget.addTab(self.logTab, "") self.inputTab = QWidget() self.inputTab.setObjectName("inputTab") self.gameTabWidget.addTab(self.inputTab, "") self.gameTabWidget.setTabText(self.gameTabWidget.indexOf(self.statusTab), "Game Status") self.gameTabWidget.setTabText(self.gameTabWidget.indexOf(self.logTab), "Game Log") self.gameTabWidget.setTabText(self.gameTabWidget.indexOf(self.inputTab), "Input") self.stackedWidget.addWidget(self.gamePage) self.gridLayout.addWidget(self.stackedWidget, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) self.stackedWidget.setCurrentIndex(0) self.createTabWidget.setCurrentIndex(0) self.gameTabWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): pass
class PatternsTable(QWidget): def __init__(self): QWidget.__init__(self) self.grid = QGridLayout() self.setLayout(self.grid) self.patternArea() self.patternTable() def createPattern(self, name, x): label = name.lower() + "Label" type = name.lower() + "Type" entry = name.lower() + "Entry" setattr(self, label, QLabel(name)) setattr(self, entry, QLineEdit()) setattr(self, type, QComboBox()) labelobj = getattr(self, label) typeobj = getattr(self, type) entryobj = getattr(self, entry) typeobj.addItem("Hexadecimal") typeobj.addItem("String") self.grid.addWidget(labelobj, x, 0) self.grid.addWidget(entryobj, x, 1) self.grid.addWidget(typeobj, x, 2) def patternArea(self): self.filetypeLabel = QLabel("File type") self.filetype = QLineEdit() self.alignedLabel = QLabel("block aligned") self.aligned = QCheckBox() self.windowLabel = QLabel("Window size") self.window = QSpinBox() self.window.setSuffix(" bytes") self.window.setRange(0, 2500000) self.window.setSingleStep(100) self.addEntry = QPushButton("add") self.connect(self.addEntry, SIGNAL("clicked()"), self.insertPattern) self.grid.addWidget(self.filetypeLabel, 0, 0) self.grid.addWidget(self.filetype, 0, 1, 1, 2) self.createPattern("Header", 2) self.createPattern("Footer", 3) self.grid.addWidget(self.windowLabel, 4, 0) self.grid.addWidget(self.window, 4, 1) self.grid.addWidget(self.alignedLabel, 5, 0) self.grid.addWidget(self.aligned, 5, 1) self.grid.addWidget(self.addEntry, 6, 1) def patternTable(self): self.patterns = QTableWidget() self.patterns.setShowGrid(False) self.patterns.setColumnCount(5) self.patterns.setHorizontalHeaderLabels(["Filetype", "Header", "Footer", "Window", "Block aligned"]) self.patterns.horizontalHeader().setStretchLastSection(True) self.connect(self.patterns.verticalHeader(), SIGNAL("sectionClicked(int)"), self.patterns.removeRow) self.grid.addWidget(self.patterns, 7, 0, 1, 3) def warning(self, msg): msgBox = QMessageBox(self) msgBox.setText(msg) msgBox.setIcon(QMessageBox.Warning) msgBox.exec_() def validate(self, **kwargs): msg = "" if len(kwargs["type"]) == 0: msg = "Type must be defined" else: for i in kwargs["type"]: if i not in string.letters: msg = "Type's characters must be in the following set\n\n" + string.letters break rowCount = self.patterns.rowCount() for row in range(0, rowCount): if str(self.patterns.item(row, 0).text()) == kwargs["type"]: msg = "Type <" + kwargs["type"] + " > already defined" if msg != "": self.warning(msg) return False if kwargs["headerType"] == "Hexadecimal" and not self.isHex(kwargs["header"]): msg = "Header must be an even number of chars" self.warning(msg) return False if len(kwargs["header"]) == 0: msg = "Header must be provided" self.warning(msg) return False if kwargs["footerType"] == "Hexadecimal" and not self.isHex(kwargs["header"]): msg = "Footer must be an even number of chars" self.warning(msg) return False if kwargs["window"] <= 0: msg = "Window size must be greater than 0" self.warning(msg) return False return True def insertPattern(self): filetype = str(self.filetype.text()) header = str(self.headerEntry.text()) headerType = str(self.headerType.currentText()) footer = str(self.footerEntry.text()) footerType = str(self.footerType.currentText()) window = self.window.text() aligned = self.aligned.isChecked() #Validate most of provided items kwargs = {"type": filetype, "header": header, "headerType": headerType, "footer": footer, "footerType": footerType, "window": int(window.replace(" bytes", ""))} if not self.validate(**kwargs): return filetypeItem = QTableWidgetItem(filetype) headerItem = QTableWidgetItem(header + " (" + headerType[0:3] + ")") footerItem = QTableWidgetItem(footer + " (" + footerType[0:3] + ")") windowItem = QTableWidgetItem(window) alignedItem = QTableWidgetItem(str(aligned)) self.patterns.insertRow(self.patterns.rowCount()) vertHeader = QTableWidgetItem(QIcon(":closetab.png"), "") row = self.patterns.rowCount() - 1 self.patterns.setVerticalHeaderItem(row, vertHeader) self.patterns.setItem(row, 0, filetypeItem) self.patterns.setItem(row, 1, headerItem) self.patterns.setItem(row, 2, footerItem) self.patterns.setItem(row, 3, windowItem) self.patterns.setItem(row, 4, alignedItem) self.patterns.resizeRowToContents(row) def isHex(self, str): HEXCHAR = "0123456789abcdefABCDEF" hexStr = "" even = False for i in range(len(str)): if str[i] in HEXCHAR: if even == True: even = False else: even = True else: return False if even: return False return True def toHex(self, str): HEXCHAR = "0123456789abcdefABCDEF" hexStr = "" evenhex = "" for i in range(len(str)): if str[i] in HEXCHAR: if len(evenhex) == 1: hexStr += chr(int(evenhex+str[i], 16)) evenhex = "" else: evenhex = str[i] else: raise ValueError, "argument 'str' contains not valid characters" if len(evenhex) != 0: raise ValueError, "argument 'str' must be an even number of char" return hexStr def textToPattern(self, text): idx = text.find("(") pattern = "" if idx != -1: type = text[idx+1:idx+4] pattern = text[0:idx-1] if type == "Hex": pattern = self.toHex(pattern) return pattern def selectedItems(self): selected = {} rowCount = self.patterns.rowCount() for row in range(0, rowCount): filetype = str(self.patterns.item(row, 0).text()) selected[filetype] = [] pattern = [] pattern.append(self.textToPattern(str(self.patterns.item(row, 1).text()))) pattern.append(self.textToPattern(str(self.patterns.item(row, 2).text()))) pattern.append(int(self.patterns.item(row, 3).text().replace(" bytes", ""))) selected[filetype].append([pattern]) if self.patterns.item(row, 4).text() == "True": selected[filetype].append(True) else: selected[filetype].append(False) return selected
def make_widget(main, show=True): id = main.persistant['id'] table = QTableWidget() table.controller = ROITableController(table, main) table.setGeometry(QRect(20, 33, 496, 296)) table.setWindowTitle('ceilingfaan - ROI Table - Work in progress') analysis = s.query(Analysis).order_by(Analysis.date.desc()).all() table.setRowCount(len(analysis)) table.setColumnCount(4) table.setHorizontalHeaderLabels( QString('CONTROL,DATE,MOUSE,FILENAME').split(',')) current_analysis = None on_render = table.controller.on('render') on_import = table.controller.on('import') for nrow, entity in enumerate(analysis): if entity.id == id: print 'Found matching analysis data', id, 'at nrow:', nrow current_analysis = entity current_nrow = nrow continue for ncol, attr in enumerate('date mouse_id filename'.split()): field = getattr(entity, attr) item = QTableWidgetItem(str(field)) item.setFlags(Qt.ItemIsEnabled) table.setItem(nrow, ncol + 1, item) render_btn = QPushButton('Render', checkable=True) render_btn.setStyleSheet('font-size: 9px; background-color: skyblue;') import_btn = QPushButton('Import') import_btn.setStyleSheet('font-size: 9px;') btn_layout = QHBoxLayout() btn_layout.setContentsMargins(5, 0, 5, 0) btn_layout.addWidget(render_btn) btn_layout.addWidget(import_btn) btn_widget = QWidget() btn_widget.nrow = nrow btn_widget.analysis_id = entity.id btn_widget.ext_roi_set = None btn_widget.setLayout(btn_layout) table.setCellWidget(nrow, 0, btn_widget) render_btn.clicked.connect(on_render) import_btn.clicked.connect(on_import) if current_analysis: table.removeRow(current_nrow) table.insertRow(0) item = QTableWidgetItem('Current Analysis') item.setFlags(Qt.ItemIsEnabled) item.setTextAlignment(Qt.AlignCenter) table.setItem(0, 0, item) for ncol, attr in enumerate('date mouse_id filename'.split()): field = getattr(current_analysis, attr) item = QTableWidgetItem(str(field)) item.setFlags(Qt.ItemIsEnabled) table.setItem(0, ncol + 1, item) # debug.enter() table.setSelectionBehavior(QTableWidget.SelectRows) table.setSelectionMode(QTableWidget.NoSelection) table.resizeColumnsToContents() table.horizontalHeader().setStretchLastSection(True) if show: table.show() return table
class GraphDialog(QDialog): edit_patterns = 0 edit_curves = 1 titles = {edit_patterns: 'Pattern editor', edit_curves: 'Curve editor'} labels = {edit_patterns: 'Patterns', edit_curves: 'Curves'} def __init__(self, dockwidget, parent, params, edit_type): QDialog.__init__(self, parent) main_lay = QVBoxLayout(self) self.dockwidget = dockwidget self.params = params self.edit_type = edit_type self.x_label = '' self.y_label = '' self.setMinimumWidth(600) self.setMinimumHeight(400) self.setWindowTitle(self.titles[edit_type]) # TODO: softcode self.setWindowModality(QtCore.Qt.ApplicationModal) self.current = None self.current_saved = False # File self.lbl_file = QLabel('File:') self.fra_file = QFrame() self.fra_file.setContentsMargins(0, 0, 0, 0) fra_file_lay = QHBoxLayout(self.fra_file) if edit_type == self.edit_patterns: self.txt_file = QLineEdit(self.params.patterns_file) elif edit_type == self.edit_curves: self.txt_file = QLineEdit(self.params.curves_file) self.txt_file.setReadOnly(True) self.txt_file.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) self.txt_file.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Minimum) fra_file_lay.addWidget(self.txt_file) self.btn_file = QPushButton('Change') # TODO: softcode self.btn_file.clicked.connect(self.import_file) fra_file_lay.addWidget(self.btn_file) fra_file_lay.setContentsMargins(0, 0, 0, 0) self.lbl_list = QLabel(self.labels[edit_type]) self.lst_list = QListWidget() self.lst_list.currentItemChanged.connect(self.list_item_changed) # Form self.fra_form = QFrame() fra_form1_lay = QFormLayout(self.fra_form) fra_form1_lay.setContentsMargins(0, 0, 0, 0) fra_form1_lay.addRow(self.lbl_list, self.lst_list) # Buttons self.fra_buttons = QFrame() fra_buttons_lay = QHBoxLayout(self.fra_buttons) fra_buttons_lay.setContentsMargins(0, 0, 0, 0) if self.edit_type == self.edit_patterns: ele_name = 'pattern' elif self.edit_type == self.edit_curves: ele_name = 'curve' self.btn_new = QPushButton('New ' + ele_name) # TODO: softcode self.btn_new.clicked.connect(self.new_element) fra_buttons_lay.addWidget(self.btn_new) self.btn_import = QPushButton('Import ' + ele_name + 's') # TODO: softcode self.btn_import.clicked.connect(self.import_file) fra_buttons_lay.addWidget(self.btn_import) self.btn_save = QPushButton('Save current ' + ele_name) # TODO: softcode self.btn_save.clicked.connect(self.save) fra_buttons_lay.addWidget(self.btn_save) self.btn_del = QPushButton('Delete current ' + ele_name) # TODO: softcode self.btn_del.clicked.connect(self.del_item) fra_buttons_lay.addWidget(self.btn_del) # ID self.lbl_id = QLabel('ID:') self.txt_id = QLineEdit() self.txt_id.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.MinimumExpanding) self.lbl_desc = QLabel('Desc.:') self.txt_desc = QLineEdit() self.fra_id = QFrame() fra_id_lay = QHBoxLayout(self.fra_id) fra_id_lay.addWidget(self.lbl_id) fra_id_lay.addWidget(self.txt_id) fra_id_lay.addWidget(self.lbl_desc) fra_id_lay.addWidget(self.txt_desc) # Table form self.table = QTableWidget(self) self.rows_nr = 24 self.cols_nr = 2 self.table.setRowCount(self.rows_nr) self.table.setColumnCount(self.cols_nr) self.table.verticalHeader().setVisible(False) # Initialize empty table self.clear_table() self.table.itemChanged.connect(self.data_changed) self.fra_table = QFrame() fra_table_lay = QVBoxLayout(self.fra_table) fra_table_lay.setContentsMargins(0, 0, 0, 0) if edit_type == self.edit_curves: self.fra_pump_type = QFrame() fra_pump_type_lay = QFormLayout(self.fra_pump_type) self.lbl_pump_type = QLabel('Curve type:') # TODO: softcode self.cbo_pump_type = QComboBox() for key, name in Curve.type_names.iteritems(): self.cbo_pump_type.addItem(name, key) fra_pump_type_lay.addRow(self.lbl_pump_type, self.cbo_pump_type) fra_table_lay.addWidget(self.fra_pump_type) self.cbo_pump_type.activated.connect(self.cbo_pump_type_activated) fra_table_lay.addWidget(self.table) self.btn_add_row = QPushButton('Add row') self.btn_add_row.clicked.connect(self.add_row) fra_table_lay.addWidget(self.btn_add_row) # Graph canvas self.fra_graph = QFrame() self.static_canvas = StaticMplCanvas(self.fra_graph, width=5, height=4, dpi=100) fra_graph_lay = QVBoxLayout(self.fra_graph) fra_graph_lay.addWidget(self.static_canvas) # Top frame self.fra_top = QFrame() fra_top_lay = QVBoxLayout(self.fra_top) fra_top_lay.addWidget(self.fra_form) fra_top_lay.addWidget(self.fra_id) fra_top_lay.addWidget(self.fra_buttons) # Bottom frame self.fra_bottom = QFrame() fra_bottom_lay = QHBoxLayout(self.fra_bottom) fra_bottom_lay.addWidget(self.fra_table) fra_bottom_lay.addWidget(self.fra_graph) # Main main_lay.addWidget(self.fra_top) main_lay.addWidget(self.fra_bottom) # Get existing patterns/curves self.need_to_update_graph = False if self.edit_type == self.edit_patterns: for pattern_id, pattern in self.params.patterns.iteritems(): self.lst_list.addItem(pattern.id) elif self.edit_type == self.edit_curves: for curve_id, curve in self.params.curves.iteritems(): self.lst_list.addItem(curve.id) if self.lst_list.count() > 0: self.lst_list.setCurrentRow(0) self.txt_id.setEnabled(True) self.txt_desc.setEnabled(True) self.btn_save.setEnabled(True) self.btn_del.setEnabled(True) self.table.setEnabled(True) self.table.setEditTriggers(QAbstractItemView.AllEditTriggers) else: self.txt_id.setEnabled(False) self.txt_desc.setEnabled(False) self.btn_save.setEnabled(False) self.btn_del.setEnabled(False) self.table.setEnabled(False) self.table.setEditTriggers(QAbstractItemView.NoEditTriggers) self.new_dialog = None self.need_to_update_graph = True def cbo_pump_type_activated(self): self.update_table_headers() self.update_graph() def add_row(self): row_pos = self.table.rowCount() self.table.insertRow(row_pos) col = 0 item = QTableWidgetItem(str(row_pos)) if self.edit_type == self.edit_patterns: self.table.setItem(row_pos, col, item) item.setFlags(QtCore.Qt.ItemIsSelectable) def setVisible(self, bool): QDialog.setVisible(self, bool) self.update_table_headers() self.update_graph() def list_item_changed(self): p_index = self.lst_list.currentRow() flags = Qt.ItemFlags() flags != Qt.ItemIsEnabled # Clear table self.clear_table() self.need_to_update_graph = False if p_index >= 0: self.table.setRowCount(0) if self.edit_type == self.edit_patterns: self.current = self.params.patterns[ self.lst_list.currentItem().text()] for v in range(len(self.current.values)): row_pos = self.table.rowCount() self.table.insertRow(row_pos) item = QTableWidgetItem(str(v)) item.setFlags(flags) self.table.setItem(v, 0, item) self.table.setItem( v, 1, QTableWidgetItem(str(self.current.values[v]))) elif self.edit_type == self.edit_curves: self.current = self.params.curves[ self.lst_list.currentItem().text()] for v in range(len(self.current.xs)): row_pos = self.table.rowCount() self.table.insertRow(row_pos) self.table.setItem( v, 0, QTableWidgetItem(str(self.current.xs[v]))) self.table.setItem( v, 1, QTableWidgetItem(str(self.current.ys[v]))) curve_type = self.current.type self.cbo_pump_type.setCurrentIndex(curve_type) # Update GUI self.txt_id.setText(self.current.id) self.txt_desc.setText(self.current.desc) self.update_table_headers() # Update graph self.need_to_update_graph = True self.update_graph() else: # No curves self.txt_id.setText('') self.txt_desc.setText('') # Update table and chart self.need_to_update_graph = False for v in range(self.table.columnCount()): self.table.setItem(v, 1, QTableWidgetItem('')) self.need_to_update_graph = True self.update_graph() def import_file(self): config_file = ConfigFile(Parameters.config_file_path) directory = None if self.edit_type == GraphDialog.edit_curves: directory = self.params.last_curves_dir elif self.edit_type == GraphDialog.edit_patterns: directory = self.params.last_patterns_dir if directory is None: directory = self.params.last_project_dir file_path = QFileDialog.getOpenFileName(self, 'Select file', directory, 'Files (*.txt *.inp)') if file_path is None or file_path == '': return else: if self.edit_type == GraphDialog.edit_patterns: # Save patterns file path in configuration file config_file.set_patterns_file_path(file_path) Parameters.patterns_file = file_path elif self.edit_type == GraphDialog.edit_curves: # Save curve file path in configuration file config_file.set_curves_file_path(file_path) Parameters.curves_file = file_path self.read(file_path) def read(self, file_path): self.lst_list.clear() if self.edit_type == self.edit_patterns: InpFile.read_patterns(self.params, file_path) for pattern_id, pattern in self.params.patterns.iteritems(): # desc = ' (' + pattern.desc + ')' if pattern.desc is not None else '' self.lst_list.addItem(pattern.id) self.params.patterns[pattern.id] = pattern elif self.edit_type == self.edit_curves: InpFile.read_curves(self.params, file_path) for curve_id, curve in self.params.curves.iteritems(): # desc = ' (' + curve.desc + ')' if curve.desc is not None else '' self.lst_list.addItem(curve.id) self.params.curves[curve.id] = curve if self.lst_list.count() > 0: self.lst_list.setCurrentRow(0) def new_element(self): old_ids = [] if self.edit_type == self.edit_patterns: for pattern in self.params.patterns.itervalues(): old_ids.append(pattern.id) elif self.edit_type == self.edit_curves: for curve in self.params.curves.itervalues(): old_ids.append(curve.id) self.new_dialog = NewIdDialog(self, old_ids) self.new_dialog.exec_() new_id = self.new_dialog.get_newid() description = self.new_dialog.get_description() if new_id is None or description is None: return if self.edit_type == self.edit_patterns: new_pattern = Pattern(new_id, description) self.params.patterns[new_pattern.id] = new_pattern self.lst_list.addItem(new_pattern.id) elif self.edit_type == self.edit_curves: curve_type = self.cbo_pump_type.itemData( self.cbo_pump_type.currentIndex()) new_curve = Curve(new_id, curve_type, desc=description) self.params.curves[new_curve.id] = new_curve self.lst_list.addItem(new_curve.id) self.lst_list.setCurrentRow(self.lst_list.count() - 1) self.txt_id.setText(new_id) self.txt_desc.setText(description) # Clear table self.clear_table() self.static_canvas.axes.clear() self.txt_id.setEnabled(True) self.txt_desc.setEnabled(True) self.btn_save.setEnabled(True) self.btn_del.setEnabled(True) self.table.setEnabled(True) self.table.setEditTriggers(QAbstractItemView.AllEditTriggers) def save(self): self.need_to_update_graph = False # Check for ID if not self.txt_id.text(): QMessageBox.warning( self, Parameters.plug_in_name, u'Please specify the ID.', # TODO: softcode QMessageBox.Ok) return if self.edit_type == GraphDialog.edit_patterns: values = [] for row in range(self.table.rowCount()): item = self.table.item(row, 1) if item is not None and item.text() != '': values.append(self.from_item_to_val(item)) else: values.append('0') pattern = Pattern(self.txt_id.text(), self.txt_desc.text(), values) old_patterns = self.params.patterns old_patterns[pattern.id] = pattern self.params.patterns = old_patterns self.lst_list.currentItem().setText(pattern.id) elif self.edit_type == GraphDialog.edit_curves: # Check for ID unique xs = [] ys = [] for row in range(self.table.rowCount()): item_x = self.table.item(row, 0) item_y = self.table.item(row, 1) if item_x.text() != '' and item_y.text() != '': xs.append(self.from_item_to_val(item_x)) ys.append(self.from_item_to_val(item_y)) curve_type = self.cbo_pump_type.itemData( self.cbo_pump_type.currentIndex()) curve = Curve(self.txt_id.text(), curve_type, self.txt_desc.text()) for v in range(len(xs)): curve.append_xy(xs[v], ys[v]) old_curves = self.params.curves old_curves[curve.id] = curve self.params.curves = old_curves self.lst_list.currentItem().setText(curve.id) # Update GUI self.dockwidget.update_curves_combo() # self.read() self.need_to_update_graph = True def clear_table(self): self.need_to_update_graph = False for r in range(self.table.rowCount()): self.table.setItem(r, 0, QTableWidgetItem(None)) self.table.setItem(r, 1, QTableWidgetItem(None)) for row in range(self.rows_nr): for col in range(self.cols_nr): if self.edit_type == self.edit_patterns: if col == 0: item = QTableWidgetItem(str(row)) self.table.setItem(row, col, item) item.setFlags(QtCore.Qt.ItemIsSelectable) # elif col == 1 and row == 0: # item = QTableWidgetItem(str(1)) # self.table.setItem(row, col, item) # item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) # elif self.edit_type == self.edit_curves: # if row == 0: # item = QTableWidgetItem(str(0)) # self.table.setItem(row, 0, item) # item = QTableWidgetItem(str(1)) # self.table.setItem(row, 1, item) # item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.need_to_update_graph = True def del_item(self): selected_row = self.lst_list.currentRow() name = self.lst_list.currentItem().text() if selected_row < 0: return self.lst_list.takeItem(selected_row) if self.lst_list.count() == 0: self.txt_id.setEnabled(False) self.txt_desc.setEnabled(False) self.btn_save.setEnabled(False) self.btn_del.setEnabled(False) self.table.setEnabled(False) self.table.setEditTriggers(QAbstractItemView.NoEditTriggers) if self.edit_type == GraphDialog.edit_curves: del self.params.curves[name] # Update GUI self.dockwidget.update_curves_combo() elif self.edit_type == GraphDialog.edit_patterns: del self.params.patterns[name] # Update GUI self.dockwidget.update_patterns_combo() def data_changed(self): if self.need_to_update_graph: self.update_graph() def update_table_headers(self): if self.edit_type == self.edit_patterns: self.x_label = 'Time period' self.y_label = 'Multiplier' elif self.edit_type == self.edit_curves: cbo_data = self.cbo_pump_type.itemData( self.cbo_pump_type.currentIndex()) if cbo_data == Curve.type_efficiency: self.x_label = 'Flow ' + '[' + self.params.options.flow_units + ']' self.y_label = 'Efficiency ' + '[' + self.params.options.units_deltaz[ self.params.options.units] + ']' if cbo_data == Curve.type_headloss: self.x_label = 'Flow ' + '[' + self.params.options.flow_units + ']' self.y_label = 'Headloss ' + '[' + self.params.options.units_deltaz[ self.params.options.units] + ']' if cbo_data == Curve.type_pump: self.x_label = 'Flow ' + '[' + self.params.options.flow_units + ']' self.y_label = 'Head ' + '[' + self.params.options.units_deltaz[ self.params.options.units] + ']' if cbo_data == Curve.type_volume: self.x_label = 'Height ' + '[' + self.params.options.flow_units + ']' self.y_label = 'Volume ' + '[' + self.params.options.units_deltaz[ self.params.options.units] + ']' self.table.setHorizontalHeaderLabels([self.x_label, self.y_label]) # TODO: softcode def update_graph(self): if not self.need_to_update_graph: return xs = [] ys = [] for row in range(self.table.rowCount()): item = self.table.item(row, 0) x = self.from_item_to_val(item) item = self.table.item(row, 1) y = self.from_item_to_val(item) if x is not None: xs.append(float(x)) if y is not None: ys.append(float(y)) if len(xs) == 0 or len(ys) == 0: self.static_canvas.clear() return xys_t = zip(xs, ys) xys_t.sort() xys = zip(*xys_t) xs = xys[0] ys = xys[1] if self.edit_type == self.edit_patterns: y_axis_label = 'Mult. avg.: ' + '{0:.2f}'.format( (numpy.average(ys))) self.static_canvas.draw_bars_graph( ys, time_period=self.params.times.pattern_timestep, y_axes_label=y_axis_label) elif self.edit_type == self.edit_curves: # Account for different types of curves cbo_data = self.cbo_pump_type.itemData( self.cbo_pump_type.currentIndex()) series_length = min(len(xs), len(ys)) # Need to account for different types of curves if cbo_data == Curve.type_efficiency or cbo_data == Curve.type_headloss or cbo_data == Curve.type_volume: self.static_canvas.draw_line_graph(xs[:series_length], ys[:series_length], self.x_label, self.y_label) elif cbo_data == Curve.type_pump: if series_length == 1 or series_length == 3: if series_length == 1: # 3 curve points curve_xs = [0, xs[0], xs[0] * 2] curve_ys = [ys[0] * 1.33, ys[0], 0] # y = a * x^2 + b * x + c elif series_length == 3: # 3 curve points curve_xs = [xs[0], xs[1], xs[2]] curve_ys = [ys[0], ys[1], ys[2]] (a, b, c) = numpy.polyfit(curve_xs, curve_ys, 2) # Create a few interpolated values interp_xs = [] interp_ys = [] n_vals = 30 for v in range(n_vals + 1): x = (curve_xs[2] - curve_xs[0]) / n_vals * v interp_xs.append(x) y = a * x**2 + b * x + c interp_ys.append(y) self.static_canvas.draw_line_graph(interp_xs, interp_ys, self.x_label, self.y_label) else: self.static_canvas.draw_line_graph(xs[:series_length], ys[:series_length], self.x_label, self.y_label) def from_item_to_val(self, item): if item is None: value = None else: value = item.text() try: value = float(value) value = max(value, 0) except: value = None return value
class Main(plugin.Plugin): " Main Class " def initialize(self, *args, **kwargs): " Init Main Class " super(Main, self).initialize(*args, **kwargs) self.scriptPath, self.scriptArgs = "", [] self.profilerPath, self.tempPath = profilerPath, tempPath self.output = " ERROR: FAIL: No output ! " self.process = QProcess() self.process.finished.connect(self.on_process_finished) self.process.error.connect(self.on_process_error) self.tabWidget, self.stat = QTabWidget(), QWidget() self.tabWidget.tabCloseRequested.connect( lambda: self.tabWidget.setTabPosition(1) if self.tabWidget. tabPosition() == 0 else self.tabWidget.setTabPosition(0)) self.tabWidget.setStyleSheet('QTabBar{font-weight:bold;}') self.tabWidget.setMovable(True) self.tabWidget.setTabsClosable(True) self.vboxlayout1 = QVBoxLayout(self.stat) self.hboxlayout1 = QHBoxLayout() self.filterTableLabel = QLabel("<b>Type to Search : </b>", self.stat) self.hboxlayout1.addWidget(self.filterTableLabel) self.filterTableLineEdit = QLineEdit(self.stat) self.filterTableLineEdit.setPlaceholderText(' Type to Search . . . ') self.hboxlayout1.addWidget(self.filterTableLineEdit) self.filterHintTableLabel = QLabel(" ? ", self.stat) self.hboxlayout1.addWidget(self.filterHintTableLabel) self.vboxlayout1.addLayout(self.hboxlayout1) self.tableWidget = QTableWidget(self.stat) self.tableWidget.setAlternatingRowColors(True) self.tableWidget.setColumnCount(8) self.tableWidget.setRowCount(2) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(0, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(1, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(2, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(3, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(4, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(5, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(6, item) item = QTableWidgetItem() self.tableWidget.setHorizontalHeaderItem(7, item) self.tableWidget.itemDoubleClicked.connect( self.on_tableWidget_itemDoubleClicked) self.vboxlayout1.addWidget(self.tableWidget) self.tabWidget.addTab(self.stat, " ? ") self.source = QWidget() self.gridlayout = QGridLayout(self.source) self.scintillaWarningLabel = QLabel( "QScintilla is not installed!. Falling back to basic text edit!.", self.source) self.gridlayout.addWidget(self.scintillaWarningLabel, 1, 0, 1, 2) self.sourceTreeWidget = QTreeWidget(self.source) self.sourceTreeWidget.setAlternatingRowColors(True) self.sourceTreeWidget.itemActivated.connect( self.on_sourceTreeWidget_itemActivated) self.sourceTreeWidget.itemClicked.connect( self.on_sourceTreeWidget_itemClicked) self.sourceTreeWidget.itemDoubleClicked.connect( self.on_sourceTreeWidget_itemClicked) self.gridlayout.addWidget(self.sourceTreeWidget, 0, 0, 1, 1) self.sourceTextEdit = QTextEdit(self.source) self.sourceTextEdit.setReadOnly(True) self.gridlayout.addWidget(self.sourceTextEdit, 0, 1, 1, 1) self.tabWidget.addTab(self.source, " ? ") self.result = QWidget() self.vlayout = QVBoxLayout(self.result) self.globalStatGroupBox = QGroupBox(self.result) self.hboxlayout = QHBoxLayout(self.globalStatGroupBox) self.totalTimeLcdNumber = QLCDNumber(self.globalStatGroupBox) self.totalTimeLcdNumber.setSegmentStyle(QLCDNumber.Filled) self.totalTimeLcdNumber.setNumDigits(7) self.totalTimeLcdNumber.display(1000000) self.totalTimeLcdNumber.setFrameShape(QFrame.StyledPanel) self.totalTimeLcdNumber.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.hboxlayout.addWidget(self.totalTimeLcdNumber) self.tTimeLabel = QLabel("<b>Total Time (Sec)</b>", self.globalStatGroupBox) self.tTimeLabel.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) self.hboxlayout.addWidget(self.tTimeLabel) self.numCallLcdNumber = QLCDNumber(self.globalStatGroupBox) self.numCallLcdNumber.setNumDigits(7) self.numCallLcdNumber.display(1000000) self.numCallLcdNumber.setSegmentStyle(QLCDNumber.Filled) self.numCallLcdNumber.setFrameShape(QFrame.StyledPanel) self.numCallLcdNumber.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.hboxlayout.addWidget(self.numCallLcdNumber) self.numCallLabel = QLabel("<b>Number of calls</b>", self.globalStatGroupBox) self.numCallLabel.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) self.hboxlayout.addWidget(self.numCallLabel) self.primCallLcdNumber = QLCDNumber(self.globalStatGroupBox) self.primCallLcdNumber.setSegmentStyle(QLCDNumber.Filled) self.primCallLcdNumber.setFrameShape(QFrame.StyledPanel) self.primCallLcdNumber.setNumDigits(7) self.primCallLcdNumber.display(1000000) self.primCallLcdNumber.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.hboxlayout.addWidget(self.primCallLcdNumber) self.primCallLabel = QLabel("<b>Primitive calls (%)</b>", self.globalStatGroupBox) self.primCallLabel.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) self.hboxlayout.addWidget(self.primCallLabel) self.vlayout.addWidget(self.globalStatGroupBox) try: from PyKDE4.kdeui import KRatingWidget self.rating = KRatingWidget(self.globalStatGroupBox) self.rating.setToolTip('Profiling Performance Rating') except ImportError: pass self.tabWidget.addTab(self.result, " Get Results ! ") self.resgraph = QWidget() self.vlayout2 = QVBoxLayout(self.result) self.graphz = QGroupBox(self.resgraph) self.hboxlayout2 = QHBoxLayout(self.graphz) try: from PyKDE4.kdeui import KLed KLed(self.graphz) except ImportError: pass self.hboxlayout2.addWidget( QLabel(''' Work in Progress :) Not Ready Yet''')) self.vlayout2.addWidget(self.graphz) self.tabWidget.addTab(self.resgraph, " Graphs and Charts ") self.pathz = QWidget() self.vlayout3 = QVBoxLayout(self.pathz) self.patz = QGroupBox(self.pathz) self.hboxlayout3 = QVBoxLayout(self.patz) self.profilepath = QLineEdit(profilerPath) self.getprofile = QPushButton(QIcon.fromTheme("document-open"), 'Open') self.getprofile.setToolTip( 'Dont touch if you dont know what are doing') self.getprofile.clicked.connect(lambda: self.profilepath.setText( str( QFileDialog.getOpenFileName( self.patz, ' Open the profile.py file ', path.expanduser("~"), ';;(profile.py)')))) self.hboxlayout3.addWidget( QLabel( '<center><b>Profile.py Python Library Full Path:</b></center>') ) self.hboxlayout3.addWidget(self.profilepath) self.hboxlayout3.addWidget(self.getprofile) self.argGroupBox = QGroupBox(self.pathz) self.hbxlayout = QHBoxLayout(self.argGroupBox) self.argLineEdit = QLineEdit(self.argGroupBox) self.argLineEdit.setToolTip( 'Not touch if you dont know what are doing') self.argLineEdit.setPlaceholderText( 'Dont touch if you dont know what are doing') self.hbxlayout.addWidget( QLabel('<b>Additional Profile Arguments:</b>')) self.hbxlayout.addWidget(self.argLineEdit) self.hboxlayout3.addWidget(self.argGroupBox) self.vlayout3.addWidget(self.patz) self.tabWidget.addTab(self.pathz, " Paths and Configs ") self.outp = QWidget() self.vlayout4 = QVBoxLayout(self.outp) self.outgro = QGroupBox(self.outp) self.outgro.setTitle(" MultiProcessing Output Logs ") self.hboxlayout4 = QVBoxLayout(self.outgro) self.outputlog = QTextEdit() self.outputlog.setText(''' I do not fear computers, I fear the lack of them. -Isaac Asimov ''') self.hboxlayout4.addWidget(self.outputlog) self.vlayout4.addWidget(self.outgro) self.tabWidget.addTab(self.outp, " Logs ") self.actionNew_profiling = QAction(QIcon.fromTheme("document-new"), 'New Profiling', self) self.actionLoad_profile = QAction(QIcon.fromTheme("document-open"), 'Open Profiling', self) self.actionClean = QAction(QIcon.fromTheme("edit-clear"), 'Clean', self) self.actionClean.triggered.connect(lambda: self.clearContent) self.actionAbout = QAction(QIcon.fromTheme("help-about"), 'About', self) self.actionAbout.triggered.connect(lambda: QMessageBox.about( self.dock, __doc__, ', '.join( (__doc__, __license__, __author__, __email__)))) self.actionSave_profile = QAction(QIcon.fromTheme("document-save"), 'Save Profiling', self) self.actionManual = QAction(QIcon.fromTheme("help-contents"), 'Help', self) self.actionManual.triggered.connect(lambda: open_new_tab( 'http://docs.python.org/library/profile.html')) self.tabWidget.setCurrentIndex(2) self.globalStatGroupBox.setTitle("Global Statistics") item = self.tableWidget.horizontalHeaderItem(0) item.setText("Number of Calls") item = self.tableWidget.horizontalHeaderItem(1) item.setText("Total Time") item = self.tableWidget.horizontalHeaderItem(2) item.setText("Per Call") item = self.tableWidget.horizontalHeaderItem(3) item.setText("Cumulative Time") item = self.tableWidget.horizontalHeaderItem(4) item.setText("Per Call") item = self.tableWidget.horizontalHeaderItem(5) item.setText("Filename") item = self.tableWidget.horizontalHeaderItem(6) item.setText("Line") item = self.tableWidget.horizontalHeaderItem(7) item.setText("Function") self.tabWidget.setTabText(self.tabWidget.indexOf(self.stat), "Statistics per Function") self.sourceTreeWidget.headerItem().setText(0, "Source files") self.tabWidget.setTabText(self.tabWidget.indexOf(self.source), "Sources Navigator") ####################################################################### self.scrollable, self.dock = QScrollArea(), QDockWidget() self.scrollable.setWidgetResizable(True) self.scrollable.setWidget(self.tabWidget) self.dock.setWindowTitle(__doc__) self.dock.setStyleSheet('QDockWidget::title{text-align: center;}') self.dock.setWidget(self.scrollable) QToolBar(self.dock).addActions( (self.actionNew_profiling, self.actionClean, self.actionSave_profile, self.actionLoad_profile, self.actionManual, self.actionAbout)) self.actionNew_profiling.triggered.connect( self.on_actionNew_profiling_triggered) self.actionLoad_profile.triggered.connect( self.on_actionLoad_profile_triggered) self.actionSave_profile.triggered.connect( self.on_actionSave_profile_triggered) self.locator.get_service('misc').add_widget( self.dock, QIcon.fromTheme("document-open-recent"), __doc__) if QSCI: # Scintilla source editor management self.scintillaWarningLabel.setText(' QScintilla is Ready ! ') layout = self.source.layout() layout.removeWidget(self.sourceTextEdit) self.sourceTextEdit = Qsci.QsciScintilla(self.source) layout.addWidget(self.sourceTextEdit, 0, 1) doc = self.sourceTextEdit doc.setLexer(Qsci.QsciLexerPython(self.sourceTextEdit)) doc.setReadOnly(True) doc.setEdgeMode(Qsci.QsciScintilla.EdgeLine) doc.setEdgeColumn(80) doc.setEdgeColor(QColor("#FF0000")) doc.setFolding(Qsci.QsciScintilla.BoxedTreeFoldStyle) doc.setBraceMatching(Qsci.QsciScintilla.SloppyBraceMatch) doc.setCaretLineVisible(True) doc.setMarginLineNumbers(1, True) doc.setMarginWidth(1, 25) doc.setTabWidth(4) doc.setEolMode(Qsci.QsciScintilla.EolUnix) self.marker = {} for color in COLORS: mnr = doc.markerDefine(Qsci.QsciScintilla.Background) doc.setMarkerBackgroundColor(color, mnr) self.marker[color] = mnr self.currentSourcePath = None # Connect table and tree filter edit signal to unique slot self.filterTableLineEdit.textEdited.connect( self.on_filterLineEdit_textEdited) # Timer to display filter hint message self.filterHintTimer = QTimer(self) self.filterHintTimer.setSingleShot(True) self.filterHintTimer.timeout.connect(self.on_filterHintTimer_timeout) # Timer to start search self.filterSearchTimer = QTimer(self) self.filterSearchTimer.setSingleShot(True) self.filterSearchTimer.timeout.connect( self.on_filterSearchTimer_timeout) self.tabLoaded = {} for i in range(10): self.tabLoaded[i] = False self.backgroundTreeMatchedItems = {} self.resizeWidgetToContent(self.tableWidget) def on_actionNew_profiling_triggered(self): self.clearContent() self.scriptPath = str( QFileDialog.getOpenFileName(self.dock, "Choose your script to profile", path.expanduser("~"), "Python (*.py *.pyw)")) commandLine = [ self.profilerPath, "-o", self.tempPath, self.scriptPath ] + self.scriptArgs commandLine = " ".join(commandLine) ##if self.termCheckBox.checkState() == Qt.Checked: #termList = ["xterm", "aterm"] #for term in termList: #termPath = which(term) #if termPath: #break #commandLine = """%s -e "%s ; echo 'Press ENTER Exit' ; read" """ \ #% (termPath, commandLine) self.process.start(commandLine) if not self.process.waitForStarted(): print((" ERROR: {} failed!".format(commandLine))) return def on_process_finished(self, exitStatus): ' whan the process end ' print((" INFO: OK: QProcess is %s" % self.process.exitCode())) self.output = self.process.readAll().data() if not self.output: self.output = " ERROR: FAIL: No output ! " self.outputlog.setText(self.output + str(self.process.exitCode())) if path.exists(self.tempPath): self.setStat(self.tempPath) remove(self.tempPath) else: self.outputlog.setText(" ERROR: QProcess FAIL: Profiling failed.") self.tabWidget.setCurrentIndex(2) def on_process_error(self, error): ' when the process fail, I hope you never see this ' print(" ERROR: QProcess FAIL: Profiler Dead, wheres your God now ? ") if error == QProcess.FailedToStart: self.outputlog.setText(" ERROR: FAIL: Profiler execution failed ") elif error == QProcess.Crashed: self.outputlog.setText(" ERROR: FAIL: Profiler execution crashed ") else: self.outputlog.setText(" ERROR: FAIL: Profiler unknown error ") def on_actionLoad_profile_triggered(self): """Load a previous profile sessions""" statPath = str( QFileDialog.getOpenFileName(self.dock, "Open profile dump", path.expanduser("~"), "Profile file (*)")) if statPath: self.clearContent() print(' INFO: OK: Loading profiling from ' + statPath) self.setStat(statPath) def on_actionSave_profile_triggered(self): """Save a profile sessions""" statPath = str( QFileDialog.getSaveFileName(self.dock, "Save profile dump", path.expanduser("~"), "Profile file (*)")) if statPath: #TODO: handle error case and give feelback to user print(' INFO: OK: Saving profiling to ' + statPath) self.stat.save(statPath) #=======================================================================# # Common parts # #=======================================================================# def on_tabWidget_currentChanged(self, index): """slot for tab change""" # Kill search and hint timer if running to avoid cross effect for timer in (self.filterHintTimer, self.filterSearchTimer): if timer.isActive(): timer.stop() if not self.stat: #No stat loaded, nothing to do return self.populateTable() self.populateSource() def on_filterLineEdit_textEdited(self, text): """slot for filter change (table or tree""" if self.filterSearchTimer.isActive(): # Already runnning, stop it self.filterSearchTimer.stop() # Start timer self.filterSearchTimer.start(300) def on_filterHintTimer_timeout(self): """Timeout to warn user about text length""" print("timeout") tab = self.tabWidget.currentIndex() if tab == TAB_FUNCTIONSTAT: label = self.filterHintTableLabel label.setText("Type > 2 characters to search") def on_filterSearchTimer_timeout(self): """timeout to start search""" tab = self.tabWidget.currentIndex() if tab == TAB_FUNCTIONSTAT: text = self.filterTableLineEdit.text() label = self.filterHintTableLabel edit = self.filterTableLineEdit widget = self.tableWidget else: print("Unknow tab for filterSearch timeout !") print(("do search for %s" % text)) if not len(text): # Empty keyword, just clean all if self.filterHintTimer.isActive(): self.filterHintTimer.stop() label.setText(" ? ") self.warnUSer(True, edit) self.clearSearch() return if len(text) < 2: # Don't filter if text is too short and tell it to user self.filterHintTimer.start(600) return else: if self.filterHintTimer.isActive(): self.filterHintTimer.stop() label.setText(" ? ") # Search self.clearSearch() matchedItems = [] if tab == TAB_FUNCTIONSTAT: # Find items matchedItems = widget.findItems(text, Qt.MatchContains) widget.setSortingEnabled(False) matchedRows = [item.row() for item in matchedItems] # Hide matched items header = widget.verticalHeader() for row in range(widget.rowCount()): if row not in matchedRows: header.hideSection(row) widget.setSortingEnabled(True) else: print(" Unknow tab for filterSearch timeout ! ") print(("got %s members" % len(matchedItems))) self.warnUSer(matchedItems, edit) self.resizeWidgetToContent(widget) def resizeWidgetToContent(self, widget): """Resize all columns according to content""" for i in range(widget.columnCount()): widget.resizeColumnToContents(i) def clearSearch(self): """Clean search result For table, show all items For tree, remove colored items""" tab = self.tabWidget.currentIndex() if tab == TAB_FUNCTIONSTAT: header = self.tableWidget.verticalHeader() if header.hiddenSectionCount(): for i in range(header.count()): if header.isSectionHidden(i): header.showSection(i) def clearContent(self): # Clear tabs self.tableWidget.clearContents() self.sourceTreeWidget.clear() # Reset LCD numbers for lcdNumber in (self.totalTimeLcdNumber, self.numCallLcdNumber, self.primCallLcdNumber): lcdNumber.display(1000000) # Reset stat self.pstat = None # Disable save as menu self.actionSave_profile.setEnabled(False) # Mark all tabs as unloaded for i in range(10): self.tabLoaded[i] = False def warnUSer(self, result, inputWidget): palette = inputWidget.palette() if result: palette.setColor(QPalette.Normal, QPalette.Base, QColor(255, 255, 255)) else: palette.setColor(QPalette.Normal, QPalette.Base, QColor(255, 136, 138)) inputWidget.setPalette(palette) inputWidget.update() def setStat(self, statPath): self.stat = Stat(path=statPath) # Global stat update self.totalTimeLcdNumber.display(self.stat.getTotalTime()) self.numCallLcdNumber.display(self.stat.getCallNumber()) self.primCallLcdNumber.display(self.stat.getPrimitiveCallRatio()) # Refresh current tab self.on_tabWidget_currentChanged(self.tabWidget.currentIndex()) # Activate save as menu self.actionSave_profile.setEnabled(True) try: self.rating.setMaxRating(10) self.rating.setRating( int(self.stat.getPrimitiveCallRatio()) / 10 - 1) except: pass #========================================================================# # Statistics table # #=======================================================================# def populateTable(self): row = 0 rowCount = self.stat.getStatNumber() progress = QProgressDialog("Populating statistics table...", "Abort", 0, 2 * rowCount) self.tableWidget.setSortingEnabled(False) self.tableWidget.setRowCount(rowCount) progress.setWindowModality(Qt.WindowModal) for (key, value) in self.stat.getStatItems(): #ncalls item = StatTableWidgetItem(str(value[0])) item.setTextAlignment(Qt.AlignRight) self.tableWidget.setItem(row, STAT_NCALLS, item) colorTableItem(item, self.stat.getCallNumber(), value[0]) #total time item = StatTableWidgetItem(str(value[2])) item.setTextAlignment(Qt.AlignRight) self.tableWidget.setItem(row, STAT_TTIME, item) colorTableItem(item, self.stat.getTotalTime(), value[2]) #per call (total time) if value[0] != 0: tPerCall = str(value[2] / value[0]) cPerCall = str(value[3] / value[0]) else: tPerCall = "" cPerCall = "" item = StatTableWidgetItem(tPerCall) item.setTextAlignment(Qt.AlignRight) self.tableWidget.setItem(row, STAT_TPERCALL, item) colorTableItem( item, 100.0 * self.stat.getTotalTime() / self.stat.getCallNumber(), tPerCall) #per call (cumulative time) item = StatTableWidgetItem(cPerCall) item.setTextAlignment(Qt.AlignRight) self.tableWidget.setItem(row, STAT_CPERCALL, item) colorTableItem( item, 100.0 * self.stat.getTotalTime() / self.stat.getCallNumber(), cPerCall) #cumulative time item = StatTableWidgetItem(str(value[3])) item.setTextAlignment(Qt.AlignRight) self.tableWidget.setItem(row, STAT_CTIME, item) colorTableItem(item, self.stat.getTotalTime(), value[3]) #Filename self.tableWidget.setItem(row, STAT_FILENAME, StatTableWidgetItem(str(key[0]))) #Line item = StatTableWidgetItem(str(key[1])) item.setTextAlignment(Qt.AlignRight) self.tableWidget.setItem(row, STAT_LINE, item) #Function name self.tableWidget.setItem(row, STAT_FUNCTION, StatTableWidgetItem(str(key[2]))) row += 1 # Store it in stat hash array self.stat.setStatLink(item, key, TAB_FUNCTIONSTAT) progress.setValue(row) if progress.wasCanceled(): return for i in range(self.tableWidget.rowCount()): progress.setValue(row + i) for j in range(self.tableWidget.columnCount()): item = self.tableWidget.item(i, j) if item: item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setSortingEnabled(True) self.resizeWidgetToContent(self.tableWidget) progress.setValue(2 * rowCount) def on_tableWidget_itemDoubleClicked(self, item): matchedItems = [] filename = str(self.tableWidget.item(item.row(), STAT_FILENAME).text()) if not filename or filename.startswith("<"): # No source code associated, return immediatly return function = self.tableWidget.item(item.row(), STAT_FUNCTION).text() line = self.tableWidget.item(item.row(), STAT_LINE).text() self.on_tabWidget_currentChanged(TAB_SOURCE) # load source tab function = "%s (%s)" % (function, line) fathers = self.sourceTreeWidget.findItems(filename, Qt.MatchContains, SOURCE_FILENAME) print(("find %s father" % len(fathers))) for father in fathers: findItems(father, function, SOURCE_FILENAME, matchedItems) print(("find %s items" % len(matchedItems))) if matchedItems: self.tabWidget.setCurrentIndex(TAB_SOURCE) self.sourceTreeWidget.scrollToItem(matchedItems[0]) self.on_sourceTreeWidget_itemClicked(matchedItems[0], SOURCE_FILENAME) matchedItems[0].setSelected(True) else: print("oups, item found but cannot scroll to it !") #=======================================================================# # Source explorer # #=====================================================================# def populateSource(self): items = {} for stat in self.stat.getStatKeys(): source = stat[0] function = "%s (%s)" % (stat[2], stat[1]) if source in ("", "profile") or source.startswith("<"): continue # Create the function child child = QTreeWidgetItem([function]) # Store it in stat hash array self.stat.setStatLink(child, stat, TAB_SOURCE) if source in items: father = items[source] else: # Create the father father = QTreeWidgetItem([source]) items[source] = father father.addChild(child) self.sourceTreeWidget.setSortingEnabled(False) for value in list(items.values()): self.sourceTreeWidget.addTopLevelItem(value) self.sourceTreeWidget.setSortingEnabled(True) def on_sourceTreeWidget_itemActivated(self, item, column): self.on_sourceTreeWidget_itemClicked(item, column) def on_sourceTreeWidget_itemClicked(self, item, column): line = 0 parent = item.parent() if QSCI: doc = self.sourceTextEdit if parent: pathz = parent.text(column) result = match("(.*) \(([0-9]+)\)", item.text(column)) if result: try: function = str(result.group(1)) line = int(result.group(2)) except ValueError: # We got garbage... falling back to line 0 pass else: pathz = item.text(column) pathz = path.abspath(str(pathz)) if self.currentSourcePath != pathz: # Need to load source self.currentSourcePath == pathz try: if QSCI: doc.clear() doc.insert(file(pathz).read()) else: self.sourceTextEdit.setPlainText(file(pathz).read()) except IOError: QMessageBox.warning(self, "Error", "Source file could not be found", QMessageBox.Ok) return if QSCI: for function, line in [(i[2], i[1]) for i in self.stat.getStatKeys() if i[0] == pathz]: # expr, regexp, case sensitive, whole word, wrap, forward doc.findFirst("def", False, True, True, False, True, line, 0, True) end, foo = doc.getCursorPosition() time = self.stat.getStatTotalTime((pathz, line, function)) colorSource(doc, self.stat.getTotalTime(), time, line, end, self.marker) if QSCI: doc.ensureLineVisible(line)
class WellMarkerDialog(QDialog): def __init__(self, well): super(WellMarkerDialog, self).__init__() self.well = well self.setupUi() self.initUI() self.button_box.accepted.connect(self.save_markers) self.button_box.rejected.connect(self.close) self.add_Button.clicked.connect(self.add_row) self.del_Button.clicked.connect(self.del_row) self.export_Button.clicked.connect(self.export_markers) self.import_Button.clicked.connect(self.import_markers) def setupUi(self): self.resize(568, 411) self.setWindowIcon(QIcon(':/icon/layer_icon')) self.setWindowTitle("Edit Markers") self.gridLayout = QGridLayout(self) # table widget self.tableWidget = QTableWidget(self) self.tableWidget.setColumnCount(4) self.tableWidget.setRowCount(0) self.tableWidget.setHorizontalHeaderItem(0, QTableWidgetItem("Name")) self.tableWidget.setHorizontalHeaderItem(1, QTableWidgetItem("TVD (m)")) self.tableWidget.setHorizontalHeaderItem(2, QTableWidgetItem("TVDSS (m)")) self.tableWidget.setHorizontalHeaderItem(3, QTableWidgetItem("Color")) self.gridLayout.addWidget(self.tableWidget, 0, 0, 1, 1) # button box self.button_box = QDialogButtonBox(self) self.export_Button = self.button_box.addButton( "Export", QDialogButtonBox.ResetRole) self.import_Button = self.button_box.addButton( "Import", QDialogButtonBox.ResetRole) self.add_Button = self.button_box.addButton("Add", QDialogButtonBox.ResetRole) self.del_Button = self.button_box.addButton("Del", QDialogButtonBox.ResetRole) self.button_box.setStandardButtons(QDialogButtonBox.Save | QDialogButtonBox.Cancel) self.gridLayout.addWidget(self.button_box, 1, 0, 1, 1) def initUI(self): self.populate_marker_table() def populate_marker_table(self): try: markers_dict = self.well.params["horizon"] for mark in markers_dict.keys(): self.tableWidget.insertRow(0) self.tableWidget.setItem(0, 0, QTableWidgetItem(mark)) self.tableWidget.setItem( 0, 1, QTableWidgetItem(str(markers_dict[mark]))) self.tableWidget.setItem( 0, 2, QTableWidgetItem(str(markers_dict[mark]))) self.tableWidget.sortItems(0, Qt.AscendingOrder) except KeyError: pass def add_row(self): self.tableWidget.insertRow(self.tableWidget.rowCount()) def del_row(self): self.tableWidget.removeRow(self.tableWidget.currentRow()) def save_markers(self): l_names = [str(self.tableWidget.item(irow, 0).text()) \ for irow in range(self.tableWidget.rowCount())] l_md = [float(self.tableWidget.item(irow, 1).text()) \ for irow in range(self.tableWidget.rowCount())] new_dict = OrderedDict([(a, b) for a, b in zip(l_names, l_md)]) if self.well.params['horizon'] != new_dict: respond = QMessageBox.question( self, "Save Markers", "Sure to save changes?", QMessageBox.Save | QMessageBox.Cancel) if respond == QMessageBox.Save: self.well.params['horizon'] = new_dict self.well.save_params() self.close() def export_markers(self): file_path = str(QFileDialog.getSaveFileName(self, "Save Markers")) l_names = [str(self.tableWidget.item(irow, 0).text()) \ for irow in range(self.tableWidget.rowCount())] l_md = [float(self.tableWidget.item(irow, 1).text()) \ for irow in range(self.tableWidget.rowCount())] df = pd.DataFrame({"name": l_names, "MD(m)": l_md}) df.to_csv(file_path, sep='\t', columns=["name", "MD(m)"], index=False) QMessageBox.information(self, "Export Markers", "Succeed!") def import_markers(self): read_csv_dialog = ReadCsvDialog() read_csv_dialog.setWindowIcon(QIcon(':/icon/layer_icon')) read_csv_dialog.setWindowTitle("Open Markers File") read_csv_dialog.label.setText("Read Makers from File") read_csv_dialog.exec_()
class Widget(QWidget): def __init__(self, parent=None): super(Widget, self).__init__(parent) buttonHelp1 = QPushButton('help') buttonHelp1.setEnabled(False) buttonHelp1.setToolTip('The table below, with the exception of the last row and column, describe the network\n' + 'in terms of the weight coefficient values. The value of a cell in the n-th row and m-th\n' + 'column is the weight of the n-th feature for the m-th animal class.\n\n' + 'As you can see, each animal class has its own neuron that recognizes it, and each of\n' + 'these neurons has inputs that receive individual feature values.\n\n' + 'The last column represents the input vector, and the last row contains the network\n' + 'output values.') buttonHelp2 = QPushButton('help') buttonHelp2.setEnabled(False) buttonHelp2.setToolTip('If you show the winner, you will see the neuron whose response was the strongest.\n' + 'This neuron indicates the animal class the examined object will most probably fall into.\n' + 'The table below, with the exception of the last row and column, describe the network\n' + 'in terms of the weight coefficient values. The value of a cell in the n-th row and m-th\n' + 'column is the weight of the n-th feature for the m-th animal class.\n\n' + 'As you can see, each animal class has its own neuron that recognizes it, and each of\n' + 'these neurons has inputs that receive individual feature values.\n\n' + 'The last column represents the input vector, and the last row contains the network\n' + 'output values.') hBoxLayout1 = QHBoxLayout() hBoxLayout1.addWidget(QLabel('The neural network in this example uses five features to recognize\n' + 'three classes of animals. Its weight coefficients are predefined and shown in the table below.\n\n' + 'To test the network behavior, enter the input signals in the rightmost column and read the output\n' + 'values from the bottom row.')) hBoxLayout1.addWidget(buttonHelp1) self.checkBoxWinner = QCheckBox() self.checkBoxWinner.setText('Show the winner') hBoxLayout2 = QHBoxLayout() hBoxLayout2.addWidget(self.checkBoxWinner) hBoxLayout2.addWidget(buttonHelp2) self.tableWidget = QTableWidget() self.labelNeuron = QLabel('(There is no winner.)') self.labelType = QLabel('This is something strange!') self.spinBoxThreshold = QDoubleSpinBox() self.spinBoxThreshold.setValue(5.0) self.groupBox = QGroupBox('Show the winner') gridLayout = QGridLayout() gridLayout.addWidget(QLabel('And the winner is...'), 0, 0) gridLayout.addWidget(self.labelNeuron, 0, 1) gridLayout.addWidget(QLabel('Because of this, the network claims:'), 1, 0) gridLayout.addWidget(self.labelType, 1, 1) gridLayout.addWidget(QLabel('Threshold:'), 2, 0) gridLayout.addWidget(self.spinBoxThreshold, 2, 1) self.groupBox.setLayout(gridLayout) self.groupBox.setVisible(False) vBoxLayout = QVBoxLayout() vBoxLayout.addLayout(hBoxLayout1) vBoxLayout.addWidget(self.tableWidget) vBoxLayout.addLayout(hBoxLayout2) vBoxLayout.addWidget(self.groupBox) self.setLayout(vBoxLayout) self.setWindowTitle('Simple linear neural network (example2)') self.classNames = ['mammal', 'bird', 'fish'] self.tableWidget.setColumnCount(5) self.tableWidget.setRowCount(6) self.tableWidget.verticalHeader().hide() self.tableWidget.setHorizontalHeaderLabels(['Feature'] + self.classNames + ['Input vector']) self.tableWidget.setCellWidget(0, 0, QLabel('number of legs')) self.tableWidget.setCellWidget(1, 0, QLabel('lives in water')) self.tableWidget.setCellWidget(2, 0, QLabel('can fly')) self.tableWidget.setCellWidget(3, 0, QLabel('has feathers')) self.tableWidget.setCellWidget(4, 0, QLabel('egg-laying')) self.tableWidget.setCellWidget(5, 0, QLabel('Output')) weights = [ [ 4, 0.01, 0.01, -1, -1.5 ], [ 2, -1, 2, 2.5, 2 ], [ -1, 3.5, 0.01, -2, 1.5 ] ] for i in xrange(len(weights)): for j in xrange(len(weights[i])): self.tableWidget.setCellWidget(j, i + 1, QLabel(' ' + str(weights[i][j]))) for i in xrange(len(weights)): self.tableWidget.setCellWidget(5, i + 1, QLabel('')) for i in xrange(len(weights[0])): doubleSpinBox = QDoubleSpinBox() doubleSpinBox.setValue(0.0) doubleSpinBox.setRange(-15.0, 15.0) self.tableWidget.setCellWidget(i, 4, doubleSpinBox) self.tableWidget.setCellWidget(5, 4, QPushButton('Calculate')) self.linearNetwork = LinearNetwork(initialWeights=weights) self.connect(self.checkBoxWinner, SIGNAL('stateChanged(int)'), self.visibleGrid) self.connect(self.tableWidget.cellWidget(5, 4), SIGNAL('clicked()'), self.updateResult) self.resize(600, 400) def visibleGrid(self, state): if state == 0: self.groupBox.setVisible(False) else: self.groupBox.setVisible(True) self.updateResult() def updateResult(self): inputColumn0 = self.tableWidget.cellWidget(0, 4).value() # number of legs inputColumn1 = self.tableWidget.cellWidget(1, 4).value() # lives in water inputColumn2 = self.tableWidget.cellWidget(2, 4).value() # can fly inputColumn3 = self.tableWidget.cellWidget(3, 4).value() # has feathers inputColumn4 = self.tableWidget.cellWidget(4, 4).value() # egg-laying outputVector = self.linearNetwork.response([inputColumn0, inputColumn1, inputColumn2, inputColumn3, inputColumn4]) if self.checkBoxWinner.checkState() == Qt.Checked: winner = LinearNetwork.winner(outputVector, self.spinBoxThreshold.value()) for i in xrange(len(outputVector)): self.tableWidget.setCellWidget(5, i + 1, QLabel()) if winner != -1: cellWinner = self.tableWidget.cellWidget(5, winner + 1) cellWinner.setStyleSheet('background-color: red;') self.labelNeuron.setText('Neuron ' + str(winner + 1)) self.labelType.setText('This is a ' + self.classNames[winner]) else: self.labelNeuron.setText('(There is no winner.)') self.labelType.setText('Thiss is something strange!') for i in xrange(len(outputVector)): self.tableWidget.cellWidget(5, i + 1).setText(str(outputVector[i]))
class VerifySetpoint(QDialog): def __init__(self, configFile, rowCount, verifyWindowDict, parent=None): super(VerifySetpoint, self).__init__(parent, Qt.CustomizeWindowHint|Qt.WindowTitleHint) self.configFile = configFile self.rowCount = rowCount self.verifyWindowDict = verifyWindowDict self.setWindowTitle('%s: setpoint v.s. readback'%self.configFile.split('/')[-1]) resolution = QDesktopWidget().screenGeometry() #self.setGeometry(resolution.width(), resolution.height() ,250, 150) self.setGeometry(resolution.width(),0, 250, 150) self.startUpdate = 1 self.keys = [] fd = open(self.configFile) lines = fd.readlines() #print(lines) setpointPVList = [] readbackPVList = [] self.allPVList = [] #thresholdList = [] rampRatePVList = [] for line in lines: #print(line.split()) setpointPVList.append(str(line.split()[0])) readbackPVList.append(str(line.split()[1])) if len(line.split())>2: #thresholdList.append(str(line.split()[2])) rampRatePVList.append(str(line.split()[2])) self.allPVList = setpointPVList + readbackPVList + rampRatePVList self.pvListColumn = 3 #print(setpointPVList) #print(readbackPVList) #print(self.allPVList) #print(thresholdList) #print(rampRatePVList) layout = QGridLayout(self) self.label = QLabel() if self.rowCount > len(readbackPVList): self.label.setText("%d PVs in the original snapshot, but only %d pairs of setpoint &\ readback PVs in this table because some setpoint PVs don't have readbacks\n\nPlease click the \ button below to update data\n"%(self.rowCount,len(readbackPVList))) else: self.label.setText("%d pairs of setpoint & readback PVs in this table\n\n \ Please click the button below to update data\n"%(len(readbackPVList))) layout.addWidget(self.label, 0, 0, 1, 2) self.table = QTableWidget() sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.table.sizePolicy().hasHeightForWidth()) self.table.setSizePolicy(sizePolicy) self.table.setMinimumSize(QSize(700, 500)) self.table.resize(self.table.sizeHint()) self.table.setRowCount(len(setpointPVList)) #if len(thresholdList): if len(rampRatePVList): #self.keys = ['setpoint PV','readback PV','SP value','RB value','diff', 'threshold'] self.keys = ['setpoint PV','readback PV','SP value (Amp)','RB value (Amp)','diff', 'ramp-rate (Amp/Sec)'] else: self.keys = ['setpoint PV','readback PV','SP value','RB value','diff'] self.table.setColumnCount(len(self.keys)) self.table.setHorizontalHeaderLabels(self.keys) layout.addWidget(self.table, 1, 0, 1, 2) #======================================================================= # toggleButton = QPushButton('Updating started', self) # toggleButton.clicked.connect(self.toggle) # layout.addWidget(toggleButton, 2, 0, 1, 1) #======================================================================= updateButton = QPushButton('Update Table', self) updateButton.clicked.connect(self.updateTable) layout.addWidget(updateButton, 2, 0, 1, 1) self.quit = QPushButton('Close Widget', self) #self.connect(self.quit, SIGNAL('clicked()'), self.close) #self.destroyed.connect(self.cleanup()) #self.deleteLater.connect(self.cleanup()) self.connect(self.quit, SIGNAL('clicked()'), self.cleanup) layout.addWidget(self.quit, 2, 1, 1, 1) self.setLayout(layout) #self.timer = cothread.Timer(2, self.updateTable, retrigger=True, reuse=True) self.updateTable() #camonitor(self.allPVList, self.callback) #t = threading.Timer(2, self.updateTable) #t.start() #=========================================================================== # def toggle(self): # source = self.sender() # if self.startUpdate: # source.setText("Updating stopped") # self.startUpdate = 0 # else: # source.setText("Updating started") # self.startUpdate = 1 # print(self.startUpdate) #=========================================================================== def __setTableItem(self, table, row, col, text): item = table.item(row, col) if item: item.setText(text) else: newitem = QTableWidgetItem(text) newitem.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable) table.setItem(row, col, newitem) #def updateTable(self): #camonitor(self.allPVList, self.callback) #cothread.WaitForQuit() def updateTable(self): #def callback(self, value, index): #while(True): #if self.startUpdate: disConnectedPVs = [] connectedPVs = [] self.table.clear() self.table.setHorizontalHeaderLabels(self.keys) self.table.setSortingEnabled(False) #print("update table:") #print(self.allPVList) #cothread.Sleep(2) connnectionStatus = connect(self.allPVList, cainfo=True, wait=False, timeout=2, throw=False) for status in connnectionStatus: if status.ok != True: disConnectedPVs.append(status.name) else: connectedPVs.append(status.name) if len(disConnectedPVs) > 0: print("%d PVs seem disconnected: \n"%len(disConnectedPVs)) print(disConnectedPVs) self.label.setText("%d PVs in the original snapshot, but only %d pairs of setpoint &\ readback in this table because some PVs don't have readbacks or they are disconnected\n\nPlease click the \ button below to update data\n"%(self.rowCount,len(connectedPVs))) self.allPVList = connectedPVs try: pvValues = caget(self.allPVList) except: print("Oops: can't get PV values to verify setpoint and readback") self.label.setText("Oops: can't get PV values to verify setpoint and readback\n\n") traceback.print_exc() return #print(pvValues) for i in range(int(len(self.allPVList)/self.pvListColumn)): self.__setTableItem(self.table, i, 0, str(self.allPVList[i]))#setpoint PV name self.__setTableItem(self.table, i, 1, str(self.allPVList[i+int(len(self.allPVList)/self.pvListColumn)])) self.__setTableItem(self.table, i, 2, str(pvValues[i])) self.__setTableItem(self.table, i, 3, str(pvValues[i+int(len(self.allPVList)/self.pvListColumn)])) diff_ = abs(pvValues[i] - pvValues[i+int(len(self.allPVList)/self.pvListColumn)]) diff = diff_.__format__('.9f') self.__setTableItem(self.table, i, 4, str(diff)) self.__setTableItem(self.table, i, 5, str(pvValues[i+int((self.pvListColumn-1)*len(self.allPVList)/self.pvListColumn)])) #self.table.resize(self.table.sizeHint()) self.table.setSortingEnabled(True) self.table.sortItems(4,1) self.table.resizeColumnsToContents() #print("end of update table:") #return 2 #self.timer.reset(2, retrigger=True) #time.sleep(2) def cleanup(self): del self.verifyWindowDict[self.configFile]#closed verifyWindow can be opened again self.close()
class PatternsTable(QWidget): def __init__(self): QWidget.__init__(self) self.grid = QGridLayout() self.setLayout(self.grid) self.patternArea() self.patternTable() def createPattern(self, name, x): label = name.lower() + "Label" type = name.lower() + "Type" entry = name.lower() + "Entry" setattr(self, label, QLabel(name)) setattr(self, entry, QLineEdit()) setattr(self, type, QComboBox()) labelobj = getattr(self, label) typeobj = getattr(self, type) entryobj = getattr(self, entry) typeobj.addItem("Hexadecimal") typeobj.addItem("String") self.grid.addWidget(labelobj, x, 0) self.grid.addWidget(entryobj, x, 1) self.grid.addWidget(typeobj, x, 2) def patternArea(self): self.filetypeLabel = QLabel("File type") self.filetype = QLineEdit() self.alignedLabel = QLabel("block aligned") self.aligned = QCheckBox() self.windowLabel = QLabel("Window size") self.window = QSpinBox() self.window.setSuffix(" bytes") self.window.setRange(0, 2500000) self.window.setSingleStep(100) self.addEntry = QPushButton("add") self.connect(self.addEntry, SIGNAL("clicked()"), self.insertPattern) self.grid.addWidget(self.filetypeLabel, 0, 0) self.grid.addWidget(self.filetype, 0, 1, 1, 2) self.createPattern("Header", 2) self.createPattern("Footer", 3) self.grid.addWidget(self.windowLabel, 4, 0) self.grid.addWidget(self.window, 4, 1) self.grid.addWidget(self.alignedLabel, 5, 0) self.grid.addWidget(self.aligned, 5, 1) self.grid.addWidget(self.addEntry, 6, 1) def patternTable(self): self.patterns = QTableWidget() self.patterns.setShowGrid(False) self.patterns.setColumnCount(5) self.patterns.setHorizontalHeaderLabels(["Filetype", "Header", "Footer", "Window", "Block aligned"]) self.patterns.horizontalHeader().setStretchLastSection(True) self.connect(self.patterns.verticalHeader(), SIGNAL("sectionClicked(int)"), self.patterns.removeRow) self.grid.addWidget(self.patterns, 7, 0, 1, 3) def warning(self, msg): msgBox = QMessageBox(self) msgBox.setText(msg) msgBox.setIcon(QMessageBox.Warning) msgBox.exec_() def validate(self, **kwargs): msg = "" if len(kwargs["type"]) == 0: msg = "Type must be defined" else: for i in kwargs["type"]: if i not in string.letters: msg = "Type's characters must be in the following set\n\n" + string.letters break rowCount = self.patterns.rowCount() for row in range(0, rowCount): if str(self.patterns.item(row, 0).text()) == kwargs["type"]: msg = "Type <" + kwargs["type"] + " > already defined" if msg != "": self.warning(msg) return False if kwargs["headerType"] == "Hexadecimal" and not self.isHex(kwargs["header"]): msg = "Header must be an even number of chars" self.warning(msg) return False if len(kwargs["header"]) == 0: msg = "Header must be provided" self.warning(msg) return False if kwargs["footerType"] == "Hexadecimal" and not self.isHex(kwargs["footer"]): msg = "Footer must be an even number of chars" self.warning(msg) return False if kwargs["window"] <= 0: msg = "Window size must be greater than 0" self.warning(msg) return False return True def insertPattern(self): filetype = str(self.filetype.text()) header = str(self.headerEntry.text()) headerType = str(self.headerType.currentText()) footer = str(self.footerEntry.text()) footerType = str(self.footerType.currentText()) window = self.window.text() aligned = self.aligned.isChecked() #Validate most of provided items kwargs = {"type": filetype, "header": header, "headerType": headerType, "footer": footer, "footerType": footerType, "window": int(window.replace(" bytes", ""))} if not self.validate(**kwargs): return filetypeItem = QTableWidgetItem(filetype) headerItem = QTableWidgetItem(header + " (" + headerType[0:3] + ")") footerItem = QTableWidgetItem(footer + " (" + footerType[0:3] + ")") windowItem = QTableWidgetItem(window) alignedItem = QTableWidgetItem(str(aligned)) self.patterns.insertRow(self.patterns.rowCount()) vertHeader = QTableWidgetItem(QIcon(":closetab.png"), "") row = self.patterns.rowCount() - 1 self.patterns.setVerticalHeaderItem(row, vertHeader) self.patterns.setItem(row, 0, filetypeItem) self.patterns.setItem(row, 1, headerItem) self.patterns.setItem(row, 2, footerItem) self.patterns.setItem(row, 3, windowItem) self.patterns.setItem(row, 4, alignedItem) self.patterns.resizeRowToContents(row) def isHex(self, hstr): HEXCHAR = "0123456789abcdefABCDEF" if len(hstr) % 2 != 0: return False even = False for i in range(len(hstr)): if hstr[i] not in HEXCHAR: return False return True def toHex(self, str): HEXCHAR = "0123456789abcdefABCDEF" hexStr = "" evenhex = "" for i in range(len(str)): if str[i] in HEXCHAR: if len(evenhex) == 1: hexStr += chr(int(evenhex+str[i], 16)) evenhex = "" else: evenhex = str[i] else: raise ValueError, "argument 'str' contains not valid characters" if len(evenhex) != 0: raise ValueError, "argument 'str' must be an even number of char" return hexStr def textToPattern(self, text): idx = text.find("(") pattern = "" if idx != -1: type = text[idx+1:idx+4] pattern = text[0:idx-1] if type == "Hex": pattern = self.toHex(pattern) return pattern def selectedItems(self): selected = {} rowCount = self.patterns.rowCount() for row in range(0, rowCount): filetype = str(self.patterns.item(row, 0).text()) selected[filetype] = [] pattern = [] pattern.append(self.textToPattern(str(self.patterns.item(row, 1).text()))) pattern.append(self.textToPattern(str(self.patterns.item(row, 2).text()))) pattern.append(int(self.patterns.item(row, 3).text().replace(" bytes", ""))) selected[filetype].append([pattern]) if self.patterns.item(row, 4).text() == "True": selected[filetype].append(True) else: selected[filetype].append(False) return selected
class ExpensesDialog(QDialog): holdc = {} def __init__(self, session, parent=None): super(ExpensesDialog, self).__init__(parent) self.session = session session = self.pullOnes('session', session) self.sessionname = str(session['name']) + ' Session' self.pagetitle = self.sessionname self.tableFont = QFont('Century Gothic', 8) #self.tableFont.setFamily('Century Gothic') self.tableHeaderStyle = "::section {" "background-color: teal; color:white}" #pull all CA self.editID = 0 self.hold_account = {} self.hold_expenses = {} self.hold_expensesGroup = {} from_label = QLabel('From:') to_label = QLabel('To:') self.fromData = QDateEdit() self.toData = QDateEdit() currentDate = QDate() self.fromData.setDate(currentDate.currentDate()) self.fromData.setCalendarPopup(True) self.toData.setDate(currentDate.currentDate()) self.toData.setCalendarPopup(True) self.pull_btn = QPushButton() self.pull_btn.setText("Load") h_pull_box = QHBoxLayout() h_pull_box.addWidget(from_label) h_pull_box.addWidget(self.fromData) h_pull_box.addWidget(to_label) h_pull_box.addWidget(self.toData) h_pull_box.addWidget(self.pull_btn) expensesGroup = self.pullGroupExpenses() account = self.pullAccount() self.expenseGroupText = QLabel('Category') self.expenseGroupData = QComboBox() self.expenseGroupData.currentIndexChanged.connect(self.reloadExpenses) self.expenseText = QLabel('Expenses') self.expenseData = QComboBox() self.amountText = QLabel('Amount') self.amountData = QLineEdit() self.amountData.setPlaceholderText('0000.00') self.tellerText = QLabel('Teller/Reciept No.') self.tellerData = QLineEdit() self.tellerData.setPlaceholderText('xxxxxxxxx') self.accountText = QLabel('Account') self.accountData = QComboBox() self.dateText = QLabel('Date') self.dateData = QDateEdit() self.dateData.setDate(currentDate.currentDate()) self.dateData.setCalendarPopup(True) self.descriptionText = QLabel('Brief Description') self.descriptionData = QPlainTextEdit() self.descriptionData.move(200, 100) hboz = QHBoxLayout() self.gender = QLabel('State') self.r1 = QRadioButton('Expenses') self.r1.setChecked(True) self.r2 = QRadioButton('Refund') hboz.addWidget(self.r1) hboz.addWidget(self.r2) i = 0 for a in expensesGroup: self.hold_expensesGroup[i] = a['id'] tex = str(a['name']).upper() self.expenseGroupData.addItem(tex) i += 1 i = 0 exp_key = self.hold_expensesGroup[self.expenseGroupData.currentIndex()] expenses = self.pullExpenses(exp_key) for a in expenses: self.hold_expenses[i] = a['id'] tex = str(a['name']).upper() self.expenseData.addItem(tex) i += 1 i = 0 for a in account: self.hold_account[i] = a['id'] tex = str(a['name']).upper() self.accountData.addItem(tex) i += 1 self.FormLayout = QFormLayout() self.FormLayout.addRow(self.expenseGroupText, self.expenseGroupData) self.FormLayout.addRow(self.expenseText, self.expenseData) self.FormLayout.addRow(self.accountText, self.accountData) self.FormLayout.addRow(self.tellerText, self.tellerData) self.FormLayout.addRow(self.amountText, self.amountData) self.FormLayout.addRow(self.gender, hboz) self.FormLayout.addRow(self.dateText, self.dateData) self.FormLayout.addRow(self.descriptionText, self.descriptionData) groupBox1 = QGroupBox('Add Expenses') groupBox1.setLayout(self.FormLayout) self.pb = QPushButton() self.pb.setObjectName("Add") self.pb.setText("Add Expenses") self.pb1 = QPushButton() self.pb1.setObjectName("Edit") self.pb1.setText("Edit Row") self.pb1.setEnabled(False) self.pb2 = QPushButton() self.pb2.setObjectName("Close") self.pb2.setText("Close") self.pb3 = QPushButton() self.pb3.setObjectName("Delete") self.pb3.setText("Delete Row") self.pb3.setEnabled(False) self.pb4 = QPushButton() self.pb4.setObjectName("Reset") self.pb4.setText("Reset") self.pb4.hide() self.pb5 = QPushButton() self.pb5.setObjectName("Change") self.pb5.setText("Change Expenses") self.pb5.hide() self.pb6 = QPushButton() self.pb6.setObjectName("Clear") self.pb6.setText("Clear Selection") self.pb6.setEnabled(False) hbo = QHBoxLayout() hbo.addWidget(self.pb) hbo.addWidget(self.pb5) hbo.addWidget(self.pb4) hbo.addWidget(self.pb2) groupBox2 = QGroupBox('Expenses Data') groupBox2.setLayout(hbo) self.cols = ['SN', 'EXPENSES', 'ACCOUNT', 'AMOUNT', 'DATE'] al = self.pullExpensesData() if len(al) > 0: al = al else: al = {} self.table = QTableWidget() header = self.table.horizontalHeader() header.setResizeMode(QHeaderView.ResizeToContents) header.setStretchLastSection(True) header.setStyleSheet(self.tableHeaderStyle) vheader = self.table.verticalHeader() vheader.setStyleSheet(self.tableHeaderStyle) # Body self.table.setWindowTitle("Expenses") self.table.resize(300, 250) self.table.setFont(self.tableFont) self.table.setSortingEnabled(2) #self.table.resizeColumnsToContents() self.table.setRowCount(len(al)) self.table.setColumnCount(len(self.cols)) self.table.setHorizontalHeaderLabels(self.cols) self.table.setContextMenuPolicy(Qt.CustomContextMenu) self.table.customContextMenuRequested.connect(self.handleHeaderMenu) self.table.hideColumn(0) self.table.setSelectionMode(QAbstractItemView.MultiSelection) self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.table.setEditTriggers(QAbstractItemView.NoEditTriggers) i = 0 for q in al: #row id self.table.setItem(i, 0, QTableWidgetItem(str(q['id']))) self.table.setItem(i, 1, QTableWidgetItem(str(q['expensename']).upper())) self.table.setItem(i, 2, QTableWidgetItem(str(q['accountname']).upper())) zamt = str("{:,}".format(float(q['amount']))) self.table.setItem(i, 3, QTableWidgetItem(zamt)) damz = float(q['datepaid']) damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y') self.table.setItem(i, 4, QTableWidgetItem(str(damt))) i += 1 self.table.itemSelectionChanged.connect(self.confirmSelection) self.table.resizeRowsToContents() v_pull_box = QVBoxLayout() self.h1_pull_box = QVBoxLayout() self.h1_pull_box.addWidget(self.table) v_pull_box.addLayout(h_pull_box) v_pull_box.addLayout(self.h1_pull_box) h2_pull_box = QHBoxLayout() h2_pull_box.addWidget(self.pb1) h2_pull_box.addWidget(self.pb3) h2_pull_box.addWidget(self.pb6) v_pull_box.addLayout(h2_pull_box) groupBox3 = QGroupBox() groupBox3.setLayout(hbo) groupBox2.setLayout(v_pull_box) grid = QGridLayout() grid.addWidget(groupBox1, 0, 0) grid.addWidget(groupBox2, 0, 1, 2, 1) grid.addWidget(groupBox3, 1, 0) self.setLayout(grid) self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click()) self.connect(self.pb1, SIGNAL("clicked()"), lambda: self.button_editshow()) self.connect(self.pb2, SIGNAL("clicked()"), lambda: self.button_close(self)) self.connect(self.pb3, SIGNAL("clicked()"), lambda: self.button_delete()) self.connect(self.pb4, SIGNAL("clicked()"), lambda: self.button_reset()) self.connect(self.pb5, SIGNAL("clicked()"), lambda: self.button_edit()) self.connect(self.pb6, SIGNAL("clicked()"), lambda: self.button_clear()) self.connect(self.pull_btn, SIGNAL("clicked()"), lambda x=1: self.reloadTable(x)) self.setWindowTitle(self.pagetitle) def handleHeaderMenu(self, pos): print('column(%d)' % self.table.horizontalHeader().logicalIndexAt(pos)) menu = QMenu() menu.addAction('Add') menu.addAction('Delete') menu.exec_(QCursor.pos()) def pullGroupExpenses(self): cn = Db() arr = cn.selectn('datas', '', '', {"pubID": 15, "active": 0}) return arr def pullExpenses(self, a): cn = Db() arr = cn.selectn('datas', '', '', {"subID": a}) return arr def pullAccount(self): cn = Db() arr = cn.selectn('datas', '', '', {"pubID": 20, "active": 0}) return arr def pullExpensesData(self): st_date = self.fromData.date().toPyDate() en_date = self.toData.date().toPyDate() st_date = time.mktime(st_date.timetuple()) en_date = time.mktime(en_date.timetuple()) db = 'school_expenses' + str(self.session) cn = Db() arr = cn.selectExpenseDate(db, st_date, en_date) return arr def mySelectTable(self): ''' get the selected rpws in a table returns list or row ids ''' sels = self.table.selectedIndexes() sels = self.table.selectionModel().selectedRows() park = [] park1 = [] for j in sels: park.append(j.row()) for i in set(park): selected = self.table.item(i, 0).text() park1.append(selected) return park1 def editRow(self, a): _session = self.session g = Db() db = 'school_expenses' + str(_session) data = g.selectn(db, '', 1, {'id': a}) if len(data) > 0: self.editID = int(data['id']) if float(data['amount']) < 0: amt = float(data['amount']) * -1 self.amountData.setText(str(amt)) self.r1.setChecked(True) else: amt = float(data['amount']) self.amountData.setText(str(amt)) self.r2.setChecked(True) self.descriptionData.clear() self.descriptionData.insertPlainText(str(data['description'])) self.tellerData.setText(str(data['teller'])) acID = self.hold_account.keys()[self.hold_account.values().index( data['accountID'])] self.accountData.setCurrentIndex(acID) exID = self.hold_expenses.keys()[self.hold_expenses.values().index( data['expenseID'])] self.expenseData.setCurrentIndex(exID) def reloadExpenses(self): cat = self.hold_expensesGroup[self.expenseGroupData.currentIndex()] expenses = self.pullExpenses(cat) self.expenseData.clear() self.hold_expenses = {} i = 0 for a in expenses: self.hold_expenses[i] = a['id'] tex = str(a['name']).upper() self.expenseData.addItem(tex) i += 1 def reloadTable(self, a): data = self.pullExpensesData() self.table.close() self.table = QTableWidget() header = self.table.horizontalHeader() header.setResizeMode(QHeaderView.ResizeToContents) header.setStretchLastSection(True) header.setStyleSheet(self.tableHeaderStyle) vheader = self.table.verticalHeader() vheader.setStyleSheet(self.tableHeaderStyle) # Body self.table.setWindowTitle("Expenses") self.table.resize(300, 250) self.table.setFont(self.tableFont) self.table.setSortingEnabled(2) self.table.resizeColumnsToContents() self.table.setRowCount(len(data)) self.table.setColumnCount(len(self.cols)) self.table.setHorizontalHeaderLabels(self.cols) self.table.setContextMenuPolicy(Qt.CustomContextMenu) self.table.customContextMenuRequested.connect(self.handleHeaderMenu) self.table.hideColumn(0) self.table.setSelectionMode(QAbstractItemView.MultiSelection) self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.table.setEditTriggers(QAbstractItemView.NoEditTriggers) i = 0 for q in data: #row id self.table.setItem(i, 0, QTableWidgetItem(str(q['id']))) self.table.setItem(i, 1, QTableWidgetItem(str(q['expensename']).upper())) self.table.setItem(i, 2, QTableWidgetItem(str(q['accountname']).upper())) zamt = str("{:,}".format(float(q['amount']))) self.table.setItem(i, 3, QTableWidgetItem(zamt)) damz = float(q['datepaid']) damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y') self.table.setItem(i, 4, QTableWidgetItem(str(damt))) i += 1 self.table.itemSelectionChanged.connect(self.confirmSelection) self.table.resizeRowsToContents() self.h1_pull_box.addWidget(self.table) self.table.show() def pullOnes(self, a, b): cn = Db() arr = cn.selectn(a, '', 1, {'id': b}) return arr def confirmSelection(self): item = self.mySelectTable() if len(item) == 1: self.pb1.setEnabled(True) self.pb3.setEnabled(True) self.pb6.setEnabled(True) elif len(item) > 1: self.pb1.setEnabled(False) self.pb3.setEnabled(True) self.pb6.setEnabled(True) else: self.pb1.setEnabled(False) self.pb3.setEnabled(False) self.pb6.setEnabled(False) def button_close(self, b): b.close() def button_editshow(self): item = self.mySelectTable() self.editRow(item[0]) self.pb.hide() self.pb4.show() self.pb5.show() def button_delete(self): item = self.mySelectTable() _session = self.session g = Db() db = 'school_expenses' + str(_session) for j in item: g.delete(db, {'id': j}) self.reloadTable(1) def button_edit(self): _session = self.session _amount = self.amountData.text() _teller = self.tellerData.text() _date = self.dateData.date().toPyDate() _date = time.mktime(_date.timetuple()) _description = self.descriptionData.toPlainText() _account = self.hold_account[self.accountData.currentIndex()] _expense = self.hold_expenses[self.expenseData.currentIndex()] if self.r1.isChecked(): _amount = float(_amount) else: _amount = float(_amount) * -1 arr = {} if _amount and not (_amount == 0) and int(_expense) > 0 and int(_account) > 0: arr['amount'] = _amount arr['datepaid'] = _date arr['description'] = _description arr['accountID'] = _account arr['expenseID'] = _expense arr['teller'] = _teller ups = {} ups['id'] = self.editID if int(self.editID) > 0: db = 'school_expenses' + str(_session) g = Db() g.update(db, arr, ups) if int(self.editID) > 0: self.button_reset() def button_reset(self): self.reloadTable(1) self.amountData.setText('') self.descriptionData.clear() self.tellerData.setText('') self.pb4.hide() self.pb5.hide() self.pb.show() self.editID = 0 self.button_clear() self.confirmSelection() def button_clear(self): self.table.selectionModel().clearSelection() def button_click(self): _session = self.session _amount = self.amountData.text() _teller = self.tellerData.text() _date = self.dateData.date().toPyDate() _date = time.mktime(_date.timetuple()) _description = self.descriptionData.toPlainText() _account = self.hold_account[self.accountData.currentIndex()] _expense = self.hold_expenses[self.expenseData.currentIndex()] if self.r1.isChecked(): _amount = float(_amount) else: _amount = float(_amount) * -1 arr = {} if _amount and not (_amount == 0) and int(_expense) > 0 and int(_account) > 0: arr['amount'] = _amount arr['datepaid'] = _date arr['description'] = _description arr['accountID'] = _account arr['expenseID'] = _expense arr['teller'] = _teller db = 'school_expenses' + str(_session) g = Db() ins = g.insert(db, arr) if int(ins) > 0: self.button_reset()
class MainForm(QDialog): def __init__(self, parent=None): super(MainForm, self).__init__(parent) self.words_to_be_learned_llist = [] self.words2sentence_list = [] self.files_table = QTableWidget() self.files_paths_list = [] self.refresh_files_table() self.files_Button = QPushButton(u"添加文章") self.zhong_kao_CheckBox = QCheckBox(u"中考词汇") self.gao_kao_CheckBox = QCheckBox(u"高考词汇") self.analysis_Button = QPushButton(u"分析") self.files_layout = QHBoxLayout() self.files_layout.addWidget(self.files_table) self.files_layout.addWidget(self.files_Button) self.a_g_layout = QHBoxLayout() self.a_g_layout.addWidget(self.zhong_kao_CheckBox) self.a_g_layout.addWidget(self.gao_kao_CheckBox) self.a_g_layout.addWidget(self.analysis_Button) # self.a_g_layout.addWidget(self.generate_Button) self.layout = QVBoxLayout() self.layout.addLayout(self.files_layout) self.layout.addLayout(self.a_g_layout) self.setLayout(self.layout) self.setWindowTitle(u"外文阅读工具") self.connect(self.files_Button, SIGNAL("clicked()"), self.addFiles) self.connect(self.analysis_Button, SIGNAL("clicked()"), self.analysis) def addFiles(self): print("addFiles") files = QFileDialog.getOpenFileNames(self, "Select Music Files", QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation)) if not files: return self.files_paths_list = files print "len_list = {0}".format(len(self.files_paths_list)) self.refresh_files_table() def refresh_files_table(self): print("refresh_files_table") self.files_table.clear() self.Y_MAX = len(self.files_paths_list) self.X_MAX = 1 self.files_table.setColumnCount(self.X_MAX) self.files_table.setRowCount(self.Y_MAX) self.files_table.setHorizontalHeaderLabels([u'文章列表'])#tips:这一句必须在setHeaderLabels之后出现 for y in range(self.Y_MAX): text = re.split("[^a-zA-Z0-9\_\.\(\)]",#这里用正则表达式,因为windows和linux下的斜杠不同 self.files_paths_list[y])[-1] item = QTableWidgetItem(u"{0}".format(text)) self.files_table.setItem(y, 0, item) def analysis(self): print("in analysis") time1 = time.time() try:#每次读取known时建立一个.bak备份吧 known_words = A_a.load_known_words() print "known_words",len(known_words) except: QMessageBox.warning(self, u"Error", u"known.txt not found!") return if len(self.files_paths_list) == 0: QMessageBox.warning(self, u"Error", u"文章列表不能为空!") return self.words_to_be_learned_llist = []#!!复原这个llist,别掉了self了 self.words2sentence_list = [] for _file in self.files_paths_list: words_to_be_learned, words_sentence = A_a.analysis_article(_file, known_words) self.words_to_be_learned_llist.append(words_to_be_learned) self.words2sentence_list.append(words_sentence) time_used = time.time() - time1 Form_analysis = F_a.analysis_Form(time_used ,self.files_paths_list, self.words_to_be_learned_llist, self.words2sentence_list) if Form_analysis.exec_(): pass
class phonesDialog(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.prm = self.parent().prm self.currLocale = self.parent().prm['currentLocale'] self.currLocale.setNumberOptions( self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator) screen = QDesktopWidget().screenGeometry() self.resize(screen.width() / 2.5, screen.height() / 3) self.isPlaying = False #self.audioManager = audioManager(self) #self.playThread = threadedPlayer(self) self.sizer = QGridLayout() self.v1Sizer = QVBoxLayout() self.v2Sizer = QVBoxLayout() self.calibSizer = QGridLayout() self.phonesTableWidget = QTableWidget() self.phonesTableWidget.setColumnCount(4) self.phonesTableWidget.setSelectionBehavior( QAbstractItemView.SelectRows) self.phonesTableWidget.setSelectionMode( QAbstractItemView.ExtendedSelection) self.phonesTableWidget.setHorizontalHeaderLabels([ self.tr('Phones'), self.tr('Max Level'), self.tr('Default'), 'id' ]) self.phonesTableWidget.hideColumn(3) self.phonesTableWidget.cellDoubleClicked[int, int].connect( self.onCellDoubleClicked) #RENAME Phones BUTTON self.renamePhonesButton = QPushButton(self.tr("Rename Phones"), self) self.renamePhonesButton.clicked.connect(self.onEditLabel) #Change Level Phones BUTTON self.changeLevelPhonesButton = QPushButton(self.tr("Change Max Level"), self) self.changeLevelPhonesButton.clicked.connect(self.onEditMaxLevel) #ADD Phones BUTTON self.addPhonesButton = QPushButton(self.tr("Add Phones"), self) self.addPhonesButton.clicked.connect(self.onClickAddPhonesButton) #REMOVE Phones BUTTON self.removePhonesButton = QPushButton(self.tr("Remove Phones"), self) self.removePhonesButton.clicked.connect(self.onClickRemovePhonesButton) #Set Default Phones BUTTON self.setDefaultPhonesButton = QPushButton(self.tr("Set Default"), self) self.setDefaultPhonesButton.clicked.connect(self.onEditDefault) self.v1Sizer.addWidget(self.renamePhonesButton) self.v1Sizer.addWidget(self.changeLevelPhonesButton) self.v1Sizer.addWidget(self.addPhonesButton) self.v1Sizer.addWidget(self.removePhonesButton) self.v1Sizer.addWidget(self.setDefaultPhonesButton) self.v1Sizer.addStretch() self.phonesList = {} for i in range(len(self.prm['phones']['phonesChoices'])): currCount = i + 1 thisID = self.prm['phones']['phonesID'][i] self.phonesList[thisID] = {} self.phonesList[thisID]['label'] = self.prm['phones'][ 'phonesChoices'][i] self.phonesList[thisID]['maxLevel'] = self.prm['phones'][ 'phonesMaxLevel'][i] self.phonesList[thisID]['default'] = self.prm['phones'][ 'defaultPhones'][i] self.phonesTableWidget.setRowCount(currCount) newItem = QTableWidgetItem(self.phonesList[thisID]['label']) newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.phonesTableWidget.setItem(currCount - 1, 0, newItem) newItem = QTableWidgetItem( self.currLocale.toString(self.phonesList[thisID]['maxLevel'])) newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.phonesTableWidget.setItem(currCount - 1, 1, newItem) newItem = QTableWidgetItem(self.phonesList[thisID]['default']) newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.phonesTableWidget.setItem(currCount - 1, 2, newItem) self.phonesList[thisID]['qid'] = QTableWidgetItem(thisID) self.phonesTableWidget.setItem(currCount - 1, 3, self.phonesList[thisID]['qid']) ##CALIBRATION TONE n = 0 self.calLabel = QLabel(self.tr('Calibration Tone:'), self) self.calibSizer.addWidget(self.calLabel, n, 0, 1, 2) n = n + 1 self.toneFreqLabel = QLabel(self.tr('Frequency (Hz)'), self) self.toneFreqTF = QLineEdit("1000") self.toneFreqTF.setValidator(QDoubleValidator(self)) self.calibSizer.addWidget(self.toneFreqLabel, n, 0) self.calibSizer.addWidget(self.toneFreqTF, n, 1) n = n + 1 self.toneLevLabel = QLabel(self.tr('Level (dB)'), self) self.toneLevTF = QLineEdit("60") self.toneLevTF.setValidator(QDoubleValidator(self)) self.calibSizer.addWidget(self.toneLevLabel, n, 0) self.calibSizer.addWidget(self.toneLevTF, n, 1) n = n + 1 self.toneDurLabel = QLabel(self.tr('Duration (ms)'), self) self.toneDurTF = QLineEdit("980") self.toneDurTF.setValidator(QDoubleValidator(self)) self.calibSizer.addWidget(self.toneDurLabel, n, 0) self.calibSizer.addWidget(self.toneDurTF, n, 1) n = n + 1 self.toneRampsLabel = QLabel(self.tr('Ramps (ms)'), self) self.toneRampsTF = QLineEdit("10") self.toneRampsTF.setValidator(QDoubleValidator(self)) self.calibSizer.addWidget(self.toneRampsLabel, n, 0) self.calibSizer.addWidget(self.toneRampsTF, n, 1) n = n + 1 self.earLabel = QLabel(self.tr('Ear:'), self) self.earChooser = QComboBox() self.earChooser.addItems( [self.tr("Right"), self.tr("Left"), self.tr("Both")]) self.calibSizer.addWidget(self.earLabel, n, 0) self.calibSizer.addWidget(self.earChooser, n, 1) n = n + 1 self.playCalibButton = QPushButton(self.tr("Play"), self) self.playCalibButton.clicked.connect(self.onClickPlayCalibButton) self.playCalibButton.setIcon( QIcon.fromTheme("media-playback-start", QIcon(":/media-playback-start"))) self.calibSizer.addWidget(self.playCalibButton, n, 0, 1, 2) n = n + 1 self.stopCalibButton = QPushButton(self.tr("Stop"), self) self.stopCalibButton.clicked.connect(self.onClickStopCalibButton) self.stopCalibButton.setIcon( QIcon.fromTheme("media-playback-stop", QIcon(":/media-playback-stop"))) self.calibSizer.addWidget(self.stopCalibButton, n, 0, 1, 2) if self.prm['pref']['sound']['playCommand'] in [ "alsaaudio", "pyaudio" ]: self.stopCalibButton.show() else: self.stopCalibButton.hide() buttonBox = QDialogButtonBox(QDialogButtonBox.Apply | QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) buttonBox.button(QDialogButtonBox.Apply).clicked.connect( self.permanentApply) self.sizer.addLayout(self.v1Sizer, 0, 0) self.v2Sizer.addLayout(self.calibSizer) self.v2Sizer.addStretch() self.sizer.addWidget(self.phonesTableWidget, 0, 1) self.sizer.addLayout(self.v2Sizer, 0, 2) self.sizer.addWidget(buttonBox, 1, 1, 1, 2) self.sizer.setColumnStretch(1, 2) self.setLayout(self.sizer) self.setWindowTitle(self.tr("Edit Phones")) self.show() def onCellDoubleClicked(self, row, col): if col == 0: self.onEditLabel() elif col == 1: self.onEditMaxLevel() elif col == 2: self.onEditDefault() def onEditLabel(self): ids = self.findSelectedItemIds() if len(ids) > 1: QMessageBox.warning( self, self.tr('Warning'), self.tr('Only one label can be renamed at a time')) elif len(ids) < 1: pass else: selectedSound = ids[0] msg = self.tr('New name:') text, ok = QInputDialog.getText(self, self.tr('Input Dialog'), msg) if ok: self.phonesTableWidget.item( self.phonesList[selectedSound]['qid'].row(), 0).setText(text) self.phonesList[selectedSound]['label'] = text def onEditMaxLevel(self): ids = self.findSelectedItemIds() if len(ids) > 1: QMessageBox.warning( self, self.tr('Warning'), self.tr('Only one item can be edited at a time')) elif len(ids) < 1: pass else: selectedSound = ids[0] msg = self.tr('Level:') text, ok = QInputDialog.getDouble( self, self.tr('Input Dialog'), msg, self.phonesList[selectedSound]['maxLevel']) if ok: self.phonesTableWidget.item( self.phonesList[selectedSound]['qid'].row(), 1).setText(self.currLocale.toString(text)) self.phonesList[selectedSound]['maxLevel'] = text def onEditDefault(self): ids = self.findSelectedItemIds() if len(ids) > 1: QMessageBox.warning( self, self.tr('Warning'), self.tr('Only one item can be edited at a time')) elif len(ids) < 1: pass else: selectedSound = ids[0] for i in range(self.phonesTableWidget.rowCount()): self.phonesTableWidget.item(i, 2).setText("\u2012") self.phonesList[str(self.phonesTableWidget.item( i, 3).text())]['default'] = "\u2012" self.phonesTableWidget.item( self.phonesList[selectedSound]['qid'].row(), 2).setText("\u2713") self.phonesList[selectedSound]['default'] = "\u2713" def findSelectedItemIds(self): selItems = self.phonesTableWidget.selectedItems() selItemsRows = [] for i in range(len(selItems)): selItemsRows.append(selItems[i].row()) selItemsRows = unique(selItemsRows) selItemsIds = [] for i in range(len(selItemsRows)): selItemsIds.append( str(self.phonesTableWidget.item(selItemsRows[i], 3).text())) return selItemsIds def permanentApply(self): self.prm['phones']['phonesChoices'] = [] self.prm['phones']['phonesMaxLevel'] = [] self.prm['phones']['defaultPhones'] = [] self.prm['phones']['phonesID'] = [] keys = sorted(self.phonesList.keys()) for key in keys: self.prm['phones']['phonesChoices'].append( str(self.phonesList[key]['label'])) self.prm['phones']['phonesMaxLevel'].append( self.phonesList[key]['maxLevel']) self.prm['phones']['defaultPhones'].append( self.phonesList[key]['default']) self.prm['phones']['phonesID'].append(key) f = open(self.parent().prm['phonesPrefFile'], 'wb') pickle.dump(self.parent().prm['phones'], f) f.close() for i in range(self.parent().phonesChooser.count()): self.parent().phonesChooser.removeItem(0) self.parent().phonesChooser.addItems( self.prm['phones']['phonesChoices']) def onClickAddPhonesButton(self): keys = sorted(self.phonesList.keys()) thisID = str(int(keys[-1]) + 1) currCount = self.phonesTableWidget.rowCount() + 1 self.phonesList[thisID] = {} self.phonesList[thisID]['label'] = 'Phones' + ' ' + str(currCount) self.phonesList[thisID]['maxLevel'] = 100 self.phonesList[thisID]['default'] = "\u2012" self.phonesTableWidget.setRowCount(currCount) newItem = QTableWidgetItem(self.phonesList[thisID]['label']) newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.phonesTableWidget.setItem(currCount - 1, 0, newItem) newItem = QTableWidgetItem( self.currLocale.toString(self.phonesList[thisID]['maxLevel'])) newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.phonesTableWidget.setItem(currCount - 1, 1, newItem) newItem = QTableWidgetItem(self.phonesList[thisID]['default']) newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.phonesTableWidget.setItem(currCount - 1, 2, newItem) self.phonesList[thisID]['qid'] = QTableWidgetItem(thisID) self.phonesTableWidget.setItem(currCount - 1, 3, self.phonesList[thisID]['qid']) def onClickRemovePhonesButton(self): if self.phonesTableWidget.rowCount() == 1: ret = QMessageBox.warning( self, self.tr("Warning"), self.tr("Only one phone left. Cannot remove!"), QMessageBox.Ok) else: ids = self.findSelectedItemIds() wasDefault = False for i in range(len(ids)): selectedPhones = ids[i] if self.phonesTableWidget.item( self.phonesList[selectedPhones]['qid'].row(), 2).text() == "\u2713": wasDefault = True self.phonesTableWidget.removeRow( self.phonesList[selectedPhones]['qid'].row()) del self.phonesList[selectedPhones] if wasDefault == True: self.phonesTableWidget.item(0, 2).setText("\u2713") self.phonesList[str(self.phonesTableWidget.item( 0, 3).text())]['default'] = "\u2713" def onClickPlayCalibButton(self): ids = self.findSelectedItemIds() if len(ids) > 1: QMessageBox.warning( self, self.tr('Warning'), self.tr('Only one label can be renamed at a time')) return elif len(ids) < 1: QMessageBox.warning(self, self.tr('Warning'), self.tr('Please, select a phone in the table')) return else: selectedSound = ids[0] calMaxLev = self.phonesList[selectedSound]['maxLevel'] frequency = self.currLocale.toDouble(self.toneFreqTF.text())[0] level = self.currLocale.toDouble(self.toneLevTF.text())[0] duration = self.currLocale.toDouble(self.toneDurTF.text())[0] ramp = self.currLocale.toDouble(self.toneRampsTF.text())[0] channel = self.earChooser.currentText() fs = self.currLocale.toInt(self.parent().sampRateTF.text())[0] nBits = self.currLocale.toInt( self.parent().nBitsChooser.currentText())[0] calTone = pureTone(frequency, 0, level, duration, ramp, channel, fs, calMaxLev) self.isPlaying = True if self.prm['pref']['sound']['playCommand'] in [ "alsaaudio", "pyaudio" ]: self.playThread = threadedAudioPlayer(self.parent()) else: self.playThread = threadedExternalAudioPlayer(self.parent()) self.playThread.playThreadedSound( calTone, fs, nBits, self.prm['pref']['sound']['playCommand'], True, 'calibrationTone.wav') if self.playThread.isFinished() == True: self.isPlaying = False def onClickStopCalibButton(self): if self.isPlaying == True: self.playThread.terminate() #self.playThread.__del__() def closeEvent(self, event): if self.isPlaying == True: #self.playThread.__del__() self.playThread.terminate() event.accept() def accept(self): #reimplement accept (i.e. ok button) if self.isPlaying == True: #self.playThread.__del__() self.playThread.terminate() QDialog.accept(self) def reject(self): #reimplement reject if self.isPlaying == True: #self.playThread.__del__() self.playThread.terminate() QDialog.reject(self)
class ProcExpWindow(QMainWindow): def __init__(self, parent=None): super().__init__(parent) # setup menu bar exitItem = QAction('Exit', self) exitItem.setShortcut('Ctrl+Q') exitItem.setStatusTip('Exit application') exitItem.triggered.connect(self.close) menuBar = self.menuBar() fileMenu = menuBar.addMenu('&File') fileMenu.addAction(exitItem) # setup widgets self.model = ProcTableModel(self) self.procTable = ProcTableWidget(self.model) self.procTable.clicked.connect(self.showDescriptors) self.handlesTable = QTableWidget() self.handlesTable.setColumnCount(2) self.handlesTable.setHorizontalHeaderLabels(('Type', 'Object Name')) self.handlesTable.verticalHeader().setVisible(False) self.handlesTable.setShowGrid(False) self.handlesTable.setSelectionBehavior(QTableWidget.SelectRows) self.handlesTable.horizontalHeader().setStretchLastSection(True) # TODO: find a way to get the row height from the QTreeView self.handlesTable.verticalHeader().setDefaultSectionSize(24) mainSplitter = QSplitter(Qt.Vertical) mainSplitter.addWidget(self.procTable) mainSplitter.addWidget(self.handlesTable) self.setCentralWidget(mainSplitter) desktopGeometry = QApplication.desktop().screenGeometry() self.setGeometry(0, 0, 1280, 700) self.move((desktopGeometry.width() - self.width()) / 2, (desktopGeometry.height() - self.height()) / 2) self.setWindowTitle('Linux Process Explorer') # find handle dialog self.findDialog = None @pyqtSlot(int) def removeFindDialog(self): self.findDialog = None def keyPressEvent(self, event): modifiers = event.modifiers() if event.key() == Qt.Key_F and modifiers & Qt.ControlModifier: if self.findDialog is None: self.findDialog = FindHandleDialog(self.model, self) self.findDialog.finished.connect(self.removeFindDialog) self.findDialog.show() else: self.findDialog.activateWindow() else: super().keyPressEvent(event) @pyqtSlot(QModelIndex) def showDescriptors(self, processMIdx): try: self.handlesTable.setRowCount(0) self.handlesTable.clearContents() descriptors = self.model.getProcDescriptors(processMIdx) libs = self.model.getProcLibraries(processMIdx) self.handlesTable.setRowCount(len(descriptors) + len(libs)) except PermissionError: self.handlesTable.setRowCount(1) self.handlesTable.setSpan(0, 0, 1, 2) permDeniedMsg = QTableWidgetItem('<Permission Denied>') permDeniedMsg.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) permDeniedMsg.setTextAlignment(Qt.AlignCenter) permDeniedMsg.setTextColor(QColor(255, 0, 0)) self.handlesTable.setItem(0, 0, permDeniedMsg) else: for row, descriptor in enumerate(descriptors): typeItem = QTableWidgetItem(descriptor.type) typeItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) nameItem = QTableWidgetItem(descriptor.name) nameItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.handlesTable.setItem(row, 0, typeItem) self.handlesTable.setItem(row, 1, nameItem) for row, libName in enumerate(libs, start=len(descriptors)): typeItem = QTableWidgetItem('Shared Library') typeItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) nameItem = QTableWidgetItem(libName) nameItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.handlesTable.setItem(row, 0, typeItem) self.handlesTable.setItem(row, 1, nameItem)
class wavListDialog(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.prm = self.parent().parent().prm self.audioManager = audioManager(self) self.currLocale = self.parent().parent().prm['currentLocale'] self.currLocale.setNumberOptions( self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator) self.isPlaying = False self.sizer = QGridLayout() self.v1Sizer = QVBoxLayout() self.wavsTableWidget = QTableWidget() self.wavsTableWidget.setColumnCount(4) self.wavsTableWidget.setSelectionBehavior(QAbstractItemView.SelectRows) self.wavsTableWidget.setSelectionMode( QAbstractItemView.ExtendedSelection) self.wavsTableWidget.setHorizontalHeaderLabels( [self.tr("File"), self.tr('Use'), self.tr("RMS Level"), 'id']) self.quidColumn = 3 self.wavsTableWidget.hideColumn(self.quidColumn) self.wavsTableWidget.cellDoubleClicked[int, int].connect( self.onCellDoubleClicked) #ADD wav BUTTON self.addWavButton = QPushButton(self.tr("Add Wav"), self) self.addWavButton.clicked.connect(self.onClickAddWavButton) #REMOVE wav BUTTON self.removeWavButton = QPushButton(self.tr("Remove Wav"), self) self.removeWavButton.clicked.connect(self.onClickRemoveWavButton) #PLAY wav BUTTON self.playWavButton = QPushButton(self.tr("Play Wav"), self) self.playWavButton.clicked.connect(self.onClickPlayWavButton) #STOP wav BUTTON self.stopWavButton = QPushButton(self.tr("Stop Playing"), self) self.stopWavButton.clicked.connect(self.onClickStopWavButton) self.v1Sizer.addWidget(self.addWavButton) self.v1Sizer.addWidget(self.removeWavButton) self.v1Sizer.addWidget(self.playWavButton) self.v1Sizer.addWidget(self.stopWavButton) self.v1Sizer.addStretch() self.wavsList = {} for i in range(len(self.parent().wavsPref['endMessageFiles'])): currCount = i + 1 thisID = self.parent().wavsPref['endMessageFilesID'][i] self.wavsList[thisID] = {} self.wavsList[thisID]['file'] = self.parent( ).wavsPref['endMessageFiles'][i] self.wavsList[thisID]['use'] = self.parent( ).wavsPref['endMessageFilesUse'][i] self.wavsList[thisID]['level'] = self.parent( ).wavsPref['endMessageLevels'][i] self.wavsTableWidget.setRowCount(currCount) n = 0 newItem = QTableWidgetItem(self.wavsList[thisID]['file']) newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.wavsTableWidget.setItem(currCount - 1, n, newItem) n = n + 1 newItem = QTableWidgetItem(self.wavsList[thisID]['use']) newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.wavsTableWidget.setItem(currCount - 1, n, newItem) n = n + 1 newItem = QTableWidgetItem( self.currLocale.toString(self.wavsList[thisID]['level'])) newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.wavsTableWidget.setItem(currCount - 1, n, newItem) n = n + 1 self.wavsList[thisID]['qid'] = QTableWidgetItem(thisID) self.wavsTableWidget.setItem(currCount - 1, n, self.wavsList[thisID]['qid']) buttonBox = QDialogButtonBox(QDialogButtonBox.Apply | QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) self.sizer.addLayout(self.v1Sizer, 0, 0) self.sizer.addWidget(self.wavsTableWidget, 0, 1) self.sizer.addWidget(buttonBox, 1, 1) self.setLayout(self.sizer) self.setWindowTitle(self.tr("Edit Wavs")) self.show() def onCellDoubleClicked(self, row, col): if col == 0: pass elif col == 1: self.onEditUse() elif col == 2: self.onEditLevel() def onEditLevel(self): ids = self.findSelectedItemIds() if len(ids) > 1: QMessageBox.warning( self, self.tr('Warning'), self.tr('Only one item can be edited at a time')) elif len(ids) < 1: pass else: selectedSound = ids[0] msg = self.tr('RMS Level:') text, ok = QInputDialog.getDouble( self, self.tr('Input Dialog'), msg, self.wavsList[selectedSound]['level']) if ok: self.wavsTableWidget.item( self.wavsList[selectedSound]['qid'].row(), 2).setText(self.currLocale.toString(text)) self.wavsList[selectedSound]['level'] = text def onEditUse(self): ids = self.findSelectedItemIds() if len(ids) > 1: QMessageBox.warning( self, self.tr('Warning'), self.tr('Only one item can be edited at a time')) elif len(ids) < 1: pass else: selectedSound = ids[0] if self.wavsTableWidget.item( self.wavsList[selectedSound]['qid'].row(), 1).text() == "\u2012": self.wavsTableWidget.item( self.wavsList[selectedSound]['qid'].row(), 1).setText("\u2713") self.wavsList[selectedSound]['use'] = "\u2713" else: self.wavsTableWidget.item( self.wavsList[selectedSound]['qid'].row(), 1).setText("\u2012") self.wavsList[selectedSound]['use'] = "\u2012" def findSelectedItemIds(self): selItems = self.wavsTableWidget.selectedItems() selItemsRows = [] for i in range(len(selItems)): selItemsRows.append(selItems[i].row()) selItemsRows = unique(selItemsRows) selItemsIds = [] for i in range(len(selItemsRows)): selItemsIds.append( str( self.wavsTableWidget.item(selItemsRows[i], self.quidColumn).text())) return selItemsIds def permanentApply(self): self.wavListToPass = {} self.wavListToPass['endMessageFiles'] = [] self.wavListToPass['endMessageFilesUse'] = [] self.wavListToPass['endMessageFilesID'] = [] self.wavListToPass['endMessageLevels'] = [] keys = sorted(self.wavsList.keys()) for key in keys: self.wavListToPass['endMessageFiles'].append( str(self.wavsList[key]['file'])) self.wavListToPass['endMessageFilesUse'].append( self.wavsList[key]['use']) self.wavListToPass['endMessageLevels'].append( self.wavsList[key]['level']) self.wavListToPass['endMessageFilesID'].append(key) def onClickAddWavButton(self): fName = QFileDialog.getOpenFileName( self, self.tr("Choose wav file to load"), '', self.tr("wav files (*.wav);;All Files (*)"))[0] if len(fName) > 0: #if the user didn't press cancel if len(self.wavsList.keys()) > 0: keys = sorted(self.wavsList.keys()) thisID = str(int(keys[-1]) + 1) else: thisID = "1" currCount = self.wavsTableWidget.rowCount() + 1 self.wavsList[thisID] = {} self.wavsList[thisID]['file'] = fName self.wavsList[thisID]['use'] = "\u2713" self.wavsList[thisID]['level'] = 60 self.wavsTableWidget.setRowCount(currCount) n = 0 newItem = QTableWidgetItem(self.wavsList[thisID]['file']) newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.wavsTableWidget.setItem(currCount - 1, n, newItem) n = n + 1 newItem = QTableWidgetItem(self.wavsList[thisID]['use']) newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.wavsTableWidget.setItem(currCount - 1, n, newItem) n = n + 1 newItem = QTableWidgetItem( self.currLocale.toString(self.wavsList[thisID]['level'])) newItem.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled) self.wavsTableWidget.setItem(currCount - 1, n, newItem) n = n + 1 self.wavsList[thisID]['qid'] = QTableWidgetItem(thisID) self.wavsTableWidget.setItem(currCount - 1, n, self.wavsList[thisID]['qid']) def onClickRemoveWavButton(self): ids = self.findSelectedItemIds() for i in range(len(ids)): selectedWavs = ids[i] self.wavsTableWidget.removeRow( self.wavsList[selectedWavs]['qid'].row()) del self.wavsList[selectedWavs] def onClickPlayWavButton(self): ids = self.findSelectedItemIds() if len(ids) < 1: QMessageBox.warning(self, self.tr('Warning'), self.tr('No files selected for playing')) else: if len(ids) > 1: pass #maybe say on the status bar that only the first one will be played selectedWav = ids[0] fName = self.wavsList[selectedWav]['file'] level = self.wavsList[selectedWav]['level'] nBits = self.currLocale.toInt( self.parent().parent().nBitsChooser.currentText())[0] maxLevel = float(self.prm['phones']['phonesMaxLevel'][ self.parent().parent().phonesChooser.currentIndex()]) msgSnd, fs = self.audioManager.loadWavFile(fName, level, maxLevel, 'Both') self.isPlaying = True if self.prm['pref']['sound']['playCommand'] in [ "alsaaudio", "pyaudio" ]: self.playThread = threadedAudioPlayer(self.parent().parent()) else: self.playThread = threadedExternalAudioPlayer( self.parent().parent()) self.playThread.playThreadedSound( msgSnd, fs, nBits, self.prm['pref']['sound']['playCommand'], False, 'tmp.wav') if self.playThread.isFinished == True: self.isPlaying = False def onClickStopWavButton(self): if self.isPlaying == True: self.playThread.terminate() def closeEvent(self, event): if self.isPlaying == True: self.playThread.terminate() event.accept() def accept(self): #reimplement accept (i.e. ok button) if self.isPlaying == True: self.playThread.terminate() QDialog.accept(self) def reject(self): #reimplement reject if self.isPlaying == True: self.playThread.terminate() QDialog.reject(self)
class ScanRecordTable(QGroupBox): """ GUI component. Displays a list of previous scan results. Selecting a scan causes details of the scan to appear in other GUI components (list of barcodes in the barcode table and image of the puck in the image frame). """ COLUMNS = [ 'Date', 'Time', 'Plate Barcode', 'Plate Type', 'Valid', 'Invalid', 'Empty' ] def __init__(self, barcode_table, image_frame, options, to_run_on_table_clicked): super(ScanRecordTable, self).__init__() # Read the store from file self._store = Store(options.store_directory.value(), options.store_capacity, FileManager()) self._options = options self._barcodeTable = barcode_table self._imageFrame = image_frame self.setTitle("Scan Records") self._init_ui(to_run_on_table_clicked) self._load_store_records() def _init_ui(self, to_run_on_table_clicked): # Create record table - lists all the records in the store self._table = QTableWidget() self._table.setFixedWidth(440) self._table.setFixedHeight(600) self._table.setColumnCount(len(self.COLUMNS)) self._table.setHorizontalHeaderLabels(self.COLUMNS) self._table.setColumnWidth(0, 70) self._table.setColumnWidth(1, 55) self._table.setColumnWidth(2, 85) self._table.setColumnWidth(3, 70) self._table.setColumnWidth(4, 45) self._table.setColumnWidth(5, 50) self._table.setColumnWidth(6, 45) self._table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) self._table.cellPressed.connect(to_run_on_table_clicked) self._table.cellPressed.connect(self._record_selected) # Delete button - deletes selected records btn_delete = QtGui.QPushButton('Delete') btn_delete.setToolTip('Delete selected scan/s') btn_delete.resize(btn_delete.sizeHint()) btn_delete.clicked.connect(self._delete_selected_records) hbox = QHBoxLayout() hbox.setSpacing(10) hbox.addWidget(btn_delete) hbox.addStretch(1) vbox = QVBoxLayout() vbox.addWidget(self._table) vbox.addLayout(hbox) self.setLayout(vbox) def add_record_frame(self, holder_barcode, plate, holder_img, pins_img): """ Add a new scan frame - creates a new record if its a new puck, else merges with previous record""" self._store.merge_record(holder_barcode, plate, holder_img, pins_img) self._load_store_records() if self._options.scan_clipboard.value(): self._barcodeTable.copy_to_clipboard() def _load_store_records(self): """ Populate the record table with all of the records in the store. """ self._table.clearContents() self._table.setRowCount(self._store.size()) for n, record in enumerate(self._store.records): items = [ record.date, record.time, record.holder_barcode, record.plate_type, record.num_valid_barcodes, record.num_unread_slots, record.num_empty_slots ] if (record.num_valid_barcodes + record.num_empty_slots) == record.num_slots: color = self._options.col_ok() else: color = self._options.col_bad() color.a = 192 for m, item in enumerate(items): new_item = QtGui.QTableWidgetItem(str(item)) new_item.setBackgroundColor(color.to_qt()) new_item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self._table.setItem(n, m, new_item) # Display the first (most recent) record self._table.setCurrentCell(0, 0) self._record_selected() def _record_selected(self): """ Called when a row is selected, causes details of the selected record to be displayed (list of barcodes in the barcode table and image of the scan in the image frame). """ try: row = self._table.selectionModel().selectedRows()[0].row() record = self._store.get_record(row) self._barcodeTable.populate(record.holder_barcode, record.barcodes) marked_image = record.marked_image(self._options) self._imageFrame.display_puck_image(marked_image) except IndexError: self._barcodeTable.clear() self._imageFrame.clear_frame( "Record table empty\nNothing to display") def _delete_selected_records(self): """ Called when the 'Delete' button is pressed. Deletes all of the selected records (and the associated images) from the store and from disk. Asks for user confirmation. """ # Display a confirmation dialog to check that user wants to proceed with deletion quit_msg = "This operation cannot be undone.\nAre you sure you want to delete these record/s?" reply = QtGui.QMessageBox.warning(self, 'Confirm Delete', quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) # If yes, find the appropriate records and delete them if reply == QtGui.QMessageBox.Yes: rows = self._table.selectionModel().selectedRows() records_to_delete = [] for row in rows: index = row.row() record = self._store.get_record(index) records_to_delete.append(record) self._store.delete_records(records_to_delete) self._load_store_records() def is_latest_holder_barcode(self, holder_barcode): return self._store.is_latest_holder_barcode(holder_barcode)
class Widget(QWidget): def __init__(self, parent=None): super(Widget, self).__init__(parent) self.programLogic = ProgramLogic() self.uiLabelStep = QLabel('Step: 1') self.uiLabelComment = QLabel('Comment:') hboxLayout1 = QHBoxLayout() hboxLayout1.addWidget(self.uiLabelStep) hboxLayout1.addWidget(self.uiLabelComment) uiGroupBox1 = QGroupBox('Before teaching') self.uiDataBefore = QTableWidget() vboxLayoutGroupBox1 = QVBoxLayout() vboxLayoutGroupBox1.addWidget(self.uiDataBefore) uiGroupBox1.setLayout(vboxLayoutGroupBox1) self.uiOutputBefore = QLineEdit() self.uiOutputBefore.setReadOnly(True) self.uiCorrectBefore = QLineEdit() self.uiCorrectBefore.setReadOnly(True) self.uiErrorBefore = QLineEdit() self.uiErrorBefore.setReadOnly(True) hboxLayout2 = QHBoxLayout() hboxLayout2.addWidget(QLabel('Output')) hboxLayout2.addWidget(self.uiOutputBefore) hboxLayout2.addWidget(QLabel('Correct output')) hboxLayout2.addWidget(self.uiCorrectBefore) hboxLayout2.addWidget(QLabel('Error')) hboxLayout2.addWidget(self.uiErrorBefore) uiGroupBox2 = QGroupBox('After teaching') self.uiDataAfter = QTableWidget() vboxLayoutGroupBox2 = QVBoxLayout() vboxLayoutGroupBox2.addWidget(self.uiDataAfter) uiGroupBox2.setLayout(vboxLayoutGroupBox2) self.uiOutputAfter= QLineEdit() self.uiOutputAfter.setReadOnly(True) self.uiCorrectAfter = QLineEdit() self.uiCorrectAfter.setReadOnly(True) self.uiErrorAfter = QLineEdit() self.uiErrorAfter.setReadOnly(True) hboxLayout3 = QHBoxLayout() hboxLayout3.addWidget(QLabel('Output')) hboxLayout3.addWidget(self.uiOutputAfter) hboxLayout3.addWidget(QLabel('Correct output')) hboxLayout3.addWidget(self.uiCorrectAfter) hboxLayout3.addWidget(QLabel('Error')) hboxLayout3.addWidget(self.uiErrorAfter) uiButtonHelp = QPushButton('help') uiButtonHelp.setEnabled(False) uiButtonHelp.setToolTip('In this step, you will teach your neuron how to respond to the sample objects provided\n' + 'in the teaching set.\n\n' + 'On the top you can see an object that is currently learned by the euron (original inputs),\n' + 'as well as its normalized version (normalized inputs). To learn ore about the normalization,\n' + 'see the book. Also, in the "weights" row, you can see the values of all neuron inputs\n' + 'BEFORE teaching.\n\n' + 'In the bottom table, there are the weights AFTER teaching.\n\n' + 'Click "Teach more!" several times to make the neuron properly recognize the supplied\n' + 'objects. You can also start the teaching process from the beginning or customize the\n' + 'teaching ratio (see the book for details).') self.uiTeachingRatio = QDoubleSpinBox() self.uiTeachingRatio.setSingleStep(0.010) self.uiTeachingRatio.setValue(0.100) self.uiButtonHistory = QPushButton('History') self.uiButonRestart = QPushButton('Restart teaching') self.uiButtonTeachMore = QPushButton('Teach more!') hboxLayout4 = QHBoxLayout() hboxLayout4.addWidget(uiButtonHelp) hboxLayout4.addWidget(QLabel('Teaching ration')) hboxLayout4.addWidget(self.uiTeachingRatio) hboxLayout4.addWidget(self.uiButtonHistory) hboxLayout4.addWidget(self.uiButonRestart) hboxLayout4.addWidget(self.uiButtonTeachMore) vboxLaouyt = QVBoxLayout() vboxLaouyt.addWidget(QLabel('<b>Teaching</b>')) vboxLaouyt.addLayout(hboxLayout1) vboxLaouyt.addWidget(uiGroupBox1) vboxLaouyt.addLayout(hboxLayout2) vboxLaouyt.addWidget(uiGroupBox2) vboxLaouyt.addLayout(hboxLayout3) vboxLaouyt.addLayout(hboxLayout4) self.setLayout(vboxLaouyt) self.uiDataBefore.setRowCount(4) self.uiDataBefore.setColumnCount(self.programLogic.inputCount()) self.uiDataBefore.horizontalHeader().hide() self.uiDataBefore.setVerticalHeaderLabels([ 'Input number (i)', 'Original inputs (u(i))', 'Normalized inputs (x(i))', 'Weights (w(i))' ]) self.uiDataAfter.setRowCount(2) self.uiDataAfter.setColumnCount(self.programLogic.inputCount()) self.uiDataAfter.horizontalHeader().hide() self.uiDataAfter.setVerticalHeaderLabels(['Input number (i)', 'Weights (w(i))']) self.showResult() def showResult(self): for i in xrange(self.programLogic.inputCount()): itemInputNumber = QTableWidgetItem() itemInputNumber.setText(str(i + 1)) itemInputNumber.setTextAlignment(Qt.AlignCenter) itemInputNumber.setFlags(Qt.ItemIsEnabled) self.uiDataBefore.setItem(0, i, itemInputNumber) itemOriginalInputs = QTableWidgetItem() originalInput = self.programLogic.currentInputs()[i] itemOriginalInputs.setText(self.formatNumber(originalInput)) itemOriginalInputs.setTextAlignment(Qt.AlignCenter) itemOriginalInputs.setFlags(Qt.ItemIsEnabled) self.uiDataBefore.setItem(1, i, itemOriginalInputs) itemNormalizedInputs = QTableWidgetItem() itemNormalizedInputs.setText(self.formatNumber(self.programLogic.currentNormalizedInputs()[i])) itemNormalizedInputs.setTextAlignment(Qt.AlignCenter) itemNormalizedInputs.setFlags(Qt.ItemIsEnabled) self.uiDataBefore.setItem(2, i, itemNormalizedInputs) itemWeights = QTableWidgetItem() itemWeights.setText(self.formatNumber(self.programLogic.currentPrevWeights()[i])) itemWeights.setTextAlignment(Qt.AlignCenter) itemWeights.setFlags(Qt.ItemIsEnabled) self.uiDataBefore.setItem(3, i, itemWeights) self.uiLabelComment.setText('Comment: ' + self.programLogic.currentComment()) self.uiCorrectBefore.setText(str(self.programLogic.currentExpectedOutput())) def formatNumber(self, value): if 0 <= value: return '+%.3f' % value return '%.3f' % value
def _init_layout(self): """ Create the GUI widgets (but leave them empty). """ hostname_combobox = QComboBox(parent=self) self._hostname_combobox = hostname_combobox hostname_combobox.setEditable(True) hostname_combobox.setSizePolicy( QSizePolicy.Expanding, QSizePolicy.Maximum ) for hostname in self._suggested_hostnames: hostname_combobox.addItem( hostname ) # EventFilter is installed after everything else is initialized. (See below.) #hostname_combobox.installEventFilter(self) self._connect_button = QPushButton("Connect", parent=self, clicked=self._handle_new_hostname) hostname_layout = QHBoxLayout() hostname_layout.addWidget( hostname_combobox ) hostname_layout.addWidget( self._connect_button ) hostinfo_table = QTableWidget() hostinfo_table.setColumnCount(len(SERVER_INFO_FIELDS)) hostinfo_table.setHorizontalHeaderLabels(SERVER_INFO_FIELDS) hostinfo_table.horizontalHeader().setVisible(True) hostinfo_table.verticalHeader().setVisible(False) hostinfo_table.setRowCount(1) hostinfo_table.setItem(0,0, QTableWidgetItem("Placeholder")) hostinfo_table.setVisible(False) hostinfo_table.resizeRowsToContents() hostinfo_table.horizontalHeader().setStretchLastSection(True) table_height = hostinfo_table.verticalHeader().sectionSize(0) + hostinfo_table.rowHeight(0) hostinfo_table.resize( QSize( hostinfo_table.width(), table_height ) ) hostinfo_table.setMaximumSize( QSize( 1000, table_height ) ) hostinfo_table.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) host_layout = QVBoxLayout() host_layout.addLayout(hostname_layout) host_layout.addWidget(hostinfo_table) host_groupbox = QGroupBox("DVID Host", parent=self) host_groupbox.setLayout( host_layout ) host_groupbox.setSizePolicy( QSizePolicy.Preferred, QSizePolicy.Preferred ) repo_treewidget = QTreeWidget(parent=self) repo_treewidget.setHeaderLabels( TREEVIEW_COLUMNS ) # TODO: Add type, shape, axes, etc. repo_treewidget.setSizePolicy( QSizePolicy.Preferred, QSizePolicy.Preferred ) repo_treewidget.itemSelectionChanged.connect( self._handle_data_selection ) data_layout = QVBoxLayout() data_layout.addWidget( repo_treewidget ) data_groupbox = QGroupBox("Data Volumes", parent=self) data_groupbox.setLayout( data_layout ) node_listwidget = QListWidget(parent=self) node_listwidget.setSizePolicy( QSizePolicy.Preferred, QSizePolicy.Preferred ) node_listwidget.itemSelectionChanged.connect( self._update_status ) node_layout = QVBoxLayout() node_layout.addWidget( node_listwidget ) node_groupbox = QGroupBox("Nodes", parent=self) node_groupbox.setLayout( node_layout ) new_data_edit = QLineEdit(parent=self) new_data_edit.textEdited.connect( self._update_status ) full_url_label = QLabel(parent=self) full_url_label.setSizePolicy( QSizePolicy.Preferred, QSizePolicy.Maximum ) text_flags = full_url_label.textInteractionFlags() full_url_label.setTextInteractionFlags( text_flags | Qt.TextSelectableByMouse ) new_data_layout = QVBoxLayout() new_data_layout.addWidget( new_data_edit ) new_data_groupbox = QGroupBox("New Data Volume", parent=self) new_data_groupbox.setLayout( new_data_layout ) new_data_groupbox.setSizePolicy( QSizePolicy.Preferred, QSizePolicy.Maximum ) buttonbox = QDialogButtonBox( Qt.Horizontal, parent=self ) buttonbox.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Cancel ) buttonbox.accepted.connect( self.accept ) buttonbox.rejected.connect( self.reject ) buttonbox.button(QDialogButtonBox.Ok).setEnabled(False) layout = QVBoxLayout() layout.addWidget( host_groupbox ) layout.addWidget( data_groupbox ) layout.addWidget( node_groupbox ) if self._mode == "specify_new": layout.addWidget( new_data_groupbox ) else: new_data_groupbox.hide() layout.addWidget( full_url_label ) layout.addWidget( buttonbox ) # Stretch factors layout.setStretchFactor(data_groupbox, 3) layout.setStretchFactor(node_groupbox, 1) self.setLayout(layout) self.setWindowTitle( "Select DVID Volume" ) self.resize(1000, 1000) # Initially disabled data_groupbox.setEnabled(False) node_groupbox.setEnabled(False) new_data_groupbox.setEnabled(False) # Set tab order self.setTabOrder(hostname_combobox, repo_treewidget) self.setTabOrder(repo_treewidget, node_listwidget) self.setTabOrder(node_listwidget, buttonbox) # Save instance members self._hostinfo_table = hostinfo_table self._data_groupbox = data_groupbox self._node_groupbox = node_groupbox self._new_data_groupbox = new_data_groupbox self._repo_treewidget = repo_treewidget self._node_listwidget = node_listwidget self._new_data_edit = new_data_edit self._full_url_label = full_url_label self._buttonbox = buttonbox # Finally install eventfilter (after everything is initialized) hostname_combobox.installEventFilter(self)
class DataItemWidget(QWidget): __EXTRA_COLUMN_WIDTH = 20 def __init__(self, me_cls, data): QWidget.__init__(self) self.__me_cls = me_cls self.__setup_ui() self.__data = data self.__init_data() self.__connect_slot() def __setup_ui(self): v_layout = QVBoxLayout() self.__tool_widget = ToolWidget() self.__tool_widget.setMaximumHeight(40) self.__data_table_widget = QTableWidget() self.__data_table_widget.horizontalHeader().setStretchLastSection(True) self.__data_table_widget.horizontalHeader().setResizeMode( 0, QHeaderView.Fixed) v_layout.setSpacing(0) v_layout.setContentsMargins(0, 0, 0, 0) v_layout.addWidget(self.__tool_widget, 0) v_layout.addWidget(self.__data_table_widget, 1) self.setLayout(v_layout) def __connect_slot(self): pass #self.connect(self.__tool_widget,SIGNAL('refresh_btn_clicked()'), self ,SLOT('__on_refresh_signal()')) def __init_data(self): self.__data_table_widget.clearContents() # init header #self.__colume_names = yt_connection.get_table_colume_names(self.__table_name) self.__colume_names = [x.field.name for x in self.__me_cls.attributes] #self.__colume_names.insert(0,'entity_id') #print self.__colume_names self.__data_table_widget.setColumnCount(len(self.__colume_names)) head_list = QStringList() for colume in self.__colume_names: head_list << colume self.__data_table_widget.setHorizontalHeaderLabels(head_list) # default the header column both sides are coverd, these codes add __EXTRA_COLUMN_WIDTH to the header column width # and reise column width in function self.__adjust_table_colume() self.__data_table_widget.horizontalHeader().setResizeMode( QHeaderView.ResizeToContents) self.__record_colume_header_width() self.__data_table_widget.horizontalHeader().setResizeMode( QHeaderView.Interactive) self.__record_colume_header_width() show_data = [] for entity_id, value in self.__data.items(): item = value.obj_data.copy() item['managed_entity_id'] = entity_id show_data.append(item) self.__update_table(show_data) # init data # data = yt_connection.get_table_data(self.__table_name) # # self.__update_table(data) self.__adjust_table_colume() def __record_colume_header_width(self): count = self.__data_table_widget.columnCount() self.__column_widths = [] for i in range(count): self.__column_widths.append( self.__data_table_widget.columnWidth(i) + self.__EXTRA_COLUMN_WIDTH) ''' data like this [ {u'direction': 'to-lport', u'name': '[]', u'priority': '100', u'log': 'true', u'action': 'drop', u'external_ids': '{"neutron:lport"="5fb77332-2035-4f72-8e57-7415b02489c9"}', u'match': '"outport==\\"inside-vm2\\""', u'severity': '[]', 'uuid': '2890a832-1c83-4b8e-8b40-2928817012cc'} ] ''' def __update_table(self, data): self.__data_table_widget.clearContents() row_num = 0 for row in data: self.__data_table_widget.insertRow(row_num) colume_num = 0 for colume in self.__colume_names: if row.has_key(colume): item_str = str(row[colume]) else: item_str = 'None' table_wid_item = QTableWidgetItem(item_str) table_wid_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) self.__data_table_widget.setItem(row_num, colume_num, table_wid_item) colume_num += 1 row_num += 1 def __clear_table_data(self): row_count = self.__data_table_widget.rowCount() rev = [i for i in range(row_count)] rev.reverse() for i in rev: self.__data_table_widget.removeRow(i) def __adjust_table_colume(self): self.__data_table_widget.resizeColumnsToContents() count = self.__data_table_widget.columnCount() for i in range(count): col_wid = self.__data_table_widget.columnWidth(i) if col_wid < self.__column_widths[i]: self.__data_table_widget.setColumnWidth( i, self.__column_widths[i])
class edycja_proby(QDialog): def __init__(self, sample, defpol={}, defpol_order=[], parent=None): ''' defpol and defpol_order should contains the same values, it will not be checked in this class is it valid, pay attention to it''' super(edycja_proby, self).__init__(parent) # self.dane = globals()["daneW"][0] # self.defpol = globals()["daneW"][1] # globals()["daneW"] = [] self.sample = copy.deepcopy(sample) self.sample._edytowany = 'E' self.org_sample = sample self.newName = self.sample.KeyCode() self.setWindowTitle("Sample: " + self.sample.KeyCode()) self.resize(691, 749) self.setMinimumSize(QSize(691, 749)) # self.setMaximumSize(QSize(691, 749)) # Prepare headers self.defpol = defpol self.defpol_order = defpol_order self.prepareDefPol() self.selected = [] # list with index of selected ring in sample # ustawienie pol z danymi self.p_naglowek = QTableWidget() self.p_naglowek.setObjectName("p_naglowek") self.p_naglowek.setColumnCount(1) self.p_naglowek.setRowCount(len(self.headers)) self.p_naglowek.setHorizontalHeaderLabels(["Value"]) self.p_naglowek.setVerticalHeaderLabels(self.headers) self.p_naglowek.setAlternatingRowColors(True) self.p_naglowek.setSortingEnabled(False) self.p_dane = QTableWidget() self.p_dane.setObjectName("p_dane") self.p_dane.setColumnCount(10) self.p_dane.setHorizontalHeaderLabels( ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]) self.dodaj = QPushButton("Add") self.usun = QPushButton("Delete") self.przerysuj = QPushButton("Redraw") self.podziel = QPushButton("Divide") self.polacz = QPushButton("Join") self.anuluj = QPushButton("Cancel") self.wykonaj = QPushButton("Update") self.vbl = QVBoxLayout() self.qmc = Qt4MplCanvas(self) self.ntb = NavigationToolbar(self.qmc, self) self.vbl.addWidget(self.qmc) self.vbl.addWidget(self.ntb) self.updateHeaderTable() self.wpisz_pomiary() self.przerysuj_wykres() # ustawiamy wyglad okna layout = QGridLayout() layout.addWidget(self.p_naglowek, 0, 0) layout1 = QGridLayout() layout1.addWidget(self.p_dane, 0, 0, 1, 5) layout1.addWidget(self.dodaj, 1, 0) layout1.addWidget(self.usun, 1, 1) layout1.addWidget(self.podziel, 1, 2) layout1.addWidget(self.polacz, 1, 3) layout1.addWidget(self.przerysuj, 1, 4) layout1.setRowMinimumHeight(1, 25) layout1.setRowStretch(0, 1) layout.addLayout(layout1, 0, 1) layout.addLayout(self.vbl, 1, 0, 1, 2) layout.addWidget(self.anuluj, 2, 0) layout.addWidget(self.wykonaj, 2, 1) layout.setColumnMinimumWidth(0, 290) layout.setColumnStretch(1, 1) layout.setRowStretch(0, 1) layout.setRowMinimumHeight(0, 350) self.setLayout(layout) # Sygnaly self.connect(self.anuluj, SIGNAL("clicked()"), self.schowaj) self.connect(self.wykonaj, SIGNAL("clicked()"), self.wykonaj_odczytanie) self.connect(self.dodaj, SIGNAL("clicked()"), self.dodaj_wartosc) self.connect(self.przerysuj, SIGNAL("clicked()"), self.przerysuj_wykres) self.connect(self.usun, SIGNAL("clicked()"), self.usun_wartosc) self.connect(self.podziel, SIGNAL("clicked()"), self.podziel_wartosc) self.connect(self.polacz, SIGNAL("clicked()"), self.polacz_wartosc) self.p_naglowek.cellChanged.connect(self.edytowana_kom_nagl) self.p_dane.itemSelectionChanged.connect(self.przerysuj_wykres) self.p_dane.cellChanged.connect(self.przerysuj_wykres) def prepareDefPol(self): """Prepare Headers for metadata, BEAWARE! measurements are delete on the end""" self.headers = [ 'KeyCode', 'DateBegin', 'DateEnd', 'Length', 'Gat', 'SapWoodRings', 'measurements', ] add_table = [] if len(self.defpol_order): add_table = self.defpol_order[:] elif len(self.defpol.keys()): add_table = sorted(list(self.defpol.keys())) else: add_table = sorted(self.sample.unikalneNaglowki()) for val in add_table: if val not in self.headers: self.headers.append(val) self.headers.remove('measurements') def updateHeaderTable(self): # Dodaj wartosci wierszow dla tabeli naglowka proby self.p_naglowek.blockSignals(True) for i, val in enumerate(self.headers): if self.sample.wypiszMetadana(val): komorka = QTableWidgetItem(str(self.sample.wypiszMetadana(val))) else: komorka = QTableWidgetItem('---') if val == 'Length': komorka.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.p_naglowek.setItem(i, 0, komorka) self.p_naglowek.blockSignals(False) def wykonaj_odczytanie(self): # spisz cala probe z edytowanych tabel i zapisz ja do zmiennej globalnej # daneW self.odczytaj_dane(origin='org') self.newName = self.org_sample.KeyCode() self.hide() def przerysuj_wykres(self): self.odczytaj_dane() self.updateHeaderTable() self.chartData = [ [], # X axis - years [], # Y axis - measurements ] self.chartData[1] = self.sample.wypiszPomiary() self.chartData[0] = range(1, self.sample.Length() + 1) self.qmc.axes.clear() # draw sample curve self.qmc.axes.plot(self.chartData[0], self.chartData[1]) # draw selected years Xpoints = [] Ypoints = [] self.selected = [] j = 0 for i in range(self.sample.Length()): if i == 11: j += 1 item = self.p_dane.item(j, i-(j*10)) if item.isSelected(): Xpoints.append(i+1) self.selected.append(i) Ypoints.append(int(item.text())) self.qmc.axes.plot(Xpoints, Ypoints, 'ro') # formatting of support lines self.qmc.axes.xaxis.set_major_locator(MultipleLocator(10)) self.qmc.axes.xaxis.set_minor_locator(MultipleLocator(2)) # Prepare axis dimensions Xmax = 40 if self.sample.Length() > 40: Xmax = self.sample.Length() + 2 Ymax = max(self.sample.wypiszPomiary()) + 30 self.qmc.axes.axis([0, Xmax, 0, Ymax]) self.qmc.axes.xaxis.grid( True, 'minor', linewidth=0.4, ls='-', color='0.20') self.qmc.axes.xaxis.grid( True, 'major', linewidth=1, ls='-', color='0.80') self.qmc.axes.tick_params(axis='both', which='major', labelsize=10) self.qmc.axes.set_axisbelow(True) # ustawienie obszaru wykresu self.qmc.axes.set_position([0.03, 0.05, 0.96, 0.94]) self.qmc.draw() def odczytaj_dane(self, origin='copy'): """update sample - read all metadata and measurements which could be altered by user. If origin of sample has to be modified use any string in origin """ if origin == 'copy': target = self.sample else: target = self.org_sample for i, head in enumerate(self.headers): ins = unicode(self.p_naglowek.item(i, 0).text()) if head not in ['Length'] and ins not in ['---', 0]: target.wpiszMetadana( head, ins ) rowNum = self.p_dane.rowCount() colNum = self.p_dane.columnCount() measurements = [] check = 'ok' redraw = 0 for w in range(rowNum): for k in range(colNum): item = self.p_dane.item(w, k) try: if int(item.text()) != 0 and str(item.text()).isdigit: measurements.append(int(item.text())) # if after notOk we find number there is something wrong # and we neef to reread measuremnts to tabel if check == 'notOk': redraw = 1 except: check = 'notOk' target.uaktualnijPom(measurements) if redraw == 1: self.wpisz_pomiary() def dodaj_wartosc(self): kk = 0 self.ile_wierszy = self.p_dane.rowCount() self.ile_kol = self.p_dane.columnCount() for wiersz in range(self.ile_wierszy): for kolumna in range(self.ile_kol): item = self.p_dane.item(wiersz, kolumna) if self.p_dane.isItemSelected(item) == True and kk == 0: kk = 1 text, ok = QInputDialog.getText( self, 'Value', 'inser value: ') if ok: measurements = self.sample.wypiszPomiary() measurements.insert((wiersz*10)+kolumna, int(text)) self.sample.uaktualnijPom(measurements) self.wpisz_pomiary() self.przerysuj_wykres() def usun_wartosc(self): sel = self.selected[:] sel.reverse() for s in sel: self.sample.usunOstatniPomiar(position=int(s)) self.wpisz_pomiary() self.przerysuj_wykres() def wpisz_pomiary(self): # przygotowanie labelek poziomych dla tablicy z pomiarami self.w = (len(self.sample.wypiszPomiary()))/10 if (len(self.sample.wypiszPomiary())) % 10 > 0: self.w += 1 i = 0 self.ww = [] while i < self.w: self.ww.append(str(i*10)) i += 1 self.p_dane.blockSignals(True) self.p_dane.clear() self.p_dane.setRowCount(self.w) self.p_dane.setVerticalHeaderLabels(self.ww) self.p_dane.setAlternatingRowColors(True) self.p_dane.setSortingEnabled(False) # Dodajemy wartosci pomiarow i = 0 j = 0 k = 0 measurements = self.sample.wypiszPomiary() while k < len(measurements): if j == 10: j = 0 i += 1 komorka = QTableWidgetItem(str(measurements[k])) self.p_dane.setItem(i, j, komorka) j += 1 k += 1 # uzupelniamy pozostale pola pustymi wartosciami while j % 10 != 0: komorka = QTableWidgetItem("") self.p_dane.setItem(i, j, komorka) j += 1 self.p_dane.resizeColumnsToContents() self.p_dane.blockSignals(False) def podziel_wartosc(self): if len(self.selected) != 1: pass else: measurements = self.sample.wypiszPomiary() val = measurements[self.selected[0]] self.divideWindow = okno_podzialu(val) self.divideWindow.exec_() measurements.pop(self.selected[0]) self.sample.uaktualnijPom(measurements) self.sample.dodajPomiar(self.divideWindow.val1, position=self.selected[0]) self.sample.dodajPomiar(self.divideWindow.val0, position=self.selected[0]) self.wpisz_pomiary() self.przerysuj_wykres() def polacz_wartosc(self): measurements = self.sample.wypiszPomiary() i = len(measurements) - 1 selectionRange = [] newMeasurements = [] while i > -1: if i in self.selected: selectionRange.append(measurements[i]) elif i not in self.selected: if len(selectionRange) > 0: newMeasurements.append(sum(selectionRange)) selectionRange = [] newMeasurements.append(measurements[i]) i -= 1 if len(selectionRange) > 0: newMeasurements.append(selectionRange) newMeasurements.reverse() self.sample.uaktualnijPom(newMeasurements) self.wpisz_pomiary() self.przerysuj_wykres() def schowaj(self): self.odczytaj_dane() self.hide() def edytowana_kom_nagl(self): # neccessary to maintain user specific date, otherwise it will be # shuflled row = self.p_naglowek.currentRow() self.p_naglowek.blockSignals(True) if self.headers[row] in ['DateBegin', 'DateEnd']: head_temp = self.headers[row] if head_temp == "DateBegin": self.sample.ustawDateBegin( int(self.p_naglowek.item(row, 0).text())) it = QTableWidgetItem(str(self.sample.DateEnd())) self.p_naglowek.setItem(self.headers.index("DateEnd"), 0, it) if head_temp == "DateEnd": self.sample.ustawDateEnd( int(self.p_naglowek.item(row, 0).text())) it = QTableWidgetItem(str(self.sample.DateBegin())) self.p_naglowek.setItem(self.headers.index("DateBegin"), 0, it) self.p_naglowek.blockSignals(False) self.przerysuj_wykres()
return my_value < other_value return super(MyTableWidgetItem, self).__lt__(other) if (__name__ == '__main__'): app = None if (QApplication.instance() is None): app = QApplication([]) widget = QTableWidget() widget.setWindowFlags(Qt.Dialog) widget.setSortingEnabled(True) widget.setRowCount(50) widget.setColumnCount(3) for row in range(50): # create a normal QTableWidgetItem a = QTableWidgetItem() a.setText(str(row)) widget.setItem(row, 0, a) # create a proper sorted item b = QTableWidgetItem() b.setData(Qt.EditRole, QVariant(row)) widget.setItem(row, 1, b) # create a custom sorted item c = MyTableWidgetItem() c.setData(Qt.EditRole, QVariant(row)) widget.setItem(row, 2, c)
class UserDialog(QDialog): holdc = {} def __init__(self, parent=None): super(UserDialog, self).__init__(parent) self.pagetitle = self.sessionname self.tableFont = QFont('Century Gothic', 8) self.table = QTableWidget() self.cols = [ 'SN', 'ITEM', 'QUANTITY', 'UNIT AMOUNT', 'TOTAL AMOUNT', 'DATE' ] self.h1_pull_box = QVBoxLayout() #self.tableFont.setFamily('Century Gothic') self.tableHeaderStyle = "::section {" "background-color: teal; color:white}" #pull all CA self.editID = 0 self.hold_unit = {} self.hold_store = {} self.hold_storeGroup = {} self.hold_borrowed = {} from_label = QLabel('From:') to_label = QLabel('To:') self.fromData = QDateEdit() self.toData = QDateEdit() currentDate = QDate() self.fromData.setDate(currentDate.currentDate()) self.fromData.setCalendarPopup(True) self.toData.setDate(currentDate.currentDate()) self.toData.setCalendarPopup(True) menu = QMenu() menu.addAction('All', lambda: self.reloadTable(0)) menu.addAction('In-Stock', lambda: self.reloadTable(1)) menu.addAction('Out-Stock', lambda: self.reloadTable(2)) menu.addAction('Damaged', lambda: self.reloadTable(3)) menu.addAction('Borrowed', lambda: self.reloadTable(4)) self.pull_btn = QPushButton() self.pull_btn.setText("Load") self.pull_btn.setMenu(menu) h_pull_box = QHBoxLayout() h_pull_box.addWidget(from_label) h_pull_box.addWidget(self.fromData) h_pull_box.addWidget(to_label) h_pull_box.addWidget(self.toData) h_pull_box.addWidget(self.pull_btn) storeGroup = self.pullGroupStore() unit = self.pullUnit() self.storeGroupText = QLabel('Category') self.storeGroupData = QComboBox() self.storeGroupData.currentIndexChanged.connect(self.reloadStore) self.storeText = QLabel('Items') self.storeData = QComboBox() self.amountText = QLabel('Total Cost') self.amountData = QLineEdit() self.amountData.setPlaceholderText('0000.00') self.tellerText = QLabel('Reciept No.') self.tellerData = QLineEdit() self.tellerData.setPlaceholderText('xxxxxxxxx') self.quantityText = QLabel('Quantity.') self.quantityData = QLineEdit() self.quantityData.setPlaceholderText('00.0') self.periodText = QLabel('Period (days)') self.periodData = QLineEdit() self.periodData.setPlaceholderText('00.0') self.personText = QLabel('Recieved By:') self.personData = QLineEdit() self.personData.setPlaceholderText('00.0') self.unitText = QLabel('Unit') self.unitData = QComboBox() self.borrowedText = QLabel('Borrowed') self.borrowedData = QComboBox() self.dateText = QLabel('Date') self.dateData = QDateEdit() self.dateData.setDate(currentDate.currentDate()) self.dateData.setCalendarPopup(True) self.descriptionText = QLabel('Description') self.descriptionData = QPlainTextEdit() self.descriptionData.move(200, 100) self.borrowedText.hide() self.borrowedData.hide() mboz = QVBoxLayout() hboz = QHBoxLayout() self.state = QLabel('') self.r1 = QRadioButton('In-stock') self.r1.setChecked(True) self.r1.toggled.connect(lambda: self.changeStates()) self.r2 = QRadioButton('Out-stock') self.r2.toggled.connect(lambda: self.changeStates()) self.r3 = QRadioButton('Damaged') self.r3.toggled.connect(lambda: self.changeStates()) self.r4 = QRadioButton('Borrowed') self.r4.toggled.connect(lambda: self.changeStates()) self.r5 = QRadioButton('Returned') self.r5.toggled.connect(lambda: self.changeStates()) hboz.addWidget(self.r1) hboz.addWidget(self.r2) hboz.addWidget(self.r3) hboz.addWidget(self.r4) hboz.addWidget(self.r5) i = 0 for a in storeGroup: self.hold_storeGroup[i] = a['id'] tex = str(a['name']).upper() self.storeGroupData.addItem(tex) i += 1 i = 0 str_key = self.hold_storeGroup[self.storeGroupData.currentIndex()] store = self.pullStore(str_key) for a in store: self.hold_store[i] = a['id'] tex = str(a['name']).upper() self.storeData.addItem(tex) i += 1 i = 0 for a in unit: self.hold_unit[i] = a['id'] tex = str(a['name']).upper() self.unitData.addItem(tex) i += 1 self.reloadBorrowed() self.FormLayout = QFormLayout() self.FormLayout.addRow(self.storeGroupText, self.storeGroupData) self.FormLayout.addRow(self.storeText, self.storeData) self.FormLayout.addRow(self.tellerText, self.tellerData) self.FormLayout.addRow(self.quantityText, self.quantityData) self.FormLayout.addRow(self.amountText, self.amountData) self.FormLayout.addRow(self.dateText, self.dateData) self.FormLayout.addRow(self.periodText, self.periodData) self.FormLayout.addRow(self.borrowedText, self.borrowedData) self.FormLayout.addRow(self.personText, self.personData) self.FormLayout.addRow(self.descriptionText, self.descriptionData) self.periodText.hide() self.periodData.hide() mboz.addLayout(hboz) mboz.addLayout(self.FormLayout) mboz.addWidget(self.state) groupBox1 = QGroupBox('Add Store Item') groupBox1.setLayout(mboz) self.pb = QPushButton() self.pb.setObjectName("Add") self.pb.setText("Add Store Item") self.pb1 = QPushButton() self.pb1.setObjectName("Edit") self.pb1.setText("Edit Row") self.pb1.setEnabled(False) self.pb2 = QPushButton() self.pb2.setObjectName("Close") self.pb2.setText("Close") self.pb3 = QPushButton() self.pb3.setObjectName("Delete") self.pb3.setText("Delete Row") self.pb3.setEnabled(False) self.pb4 = QPushButton() self.pb4.setObjectName("Reset") self.pb4.setText("Reset") self.pb4.hide() self.pb5 = QPushButton() self.pb5.setObjectName("Change") self.pb5.setText("Change Store") self.pb5.hide() self.pb6 = QPushButton() self.pb6.setObjectName("Clear") self.pb6.setText("Clear Selection") self.pb6.setEnabled(False) hbo = QHBoxLayout() hbo.addWidget(self.pb) hbo.addWidget(self.pb5) hbo.addWidget(self.pb4) hbo.addWidget(self.pb2) groupBox2 = QGroupBox('Store Data') groupBox2.setLayout(hbo) al = self.pullStoreData(0) if al and len(al) > 0: al = al else: al = {} self.storeData.currentIndexChanged.connect( lambda: self.reloadBorrowed()) header = self.table.horizontalHeader() header.setResizeMode(QHeaderView.ResizeToContents) header.setStretchLastSection(True) header.setStyleSheet(self.tableHeaderStyle) vheader = self.table.verticalHeader() vheader.setStyleSheet(self.tableHeaderStyle) # Body self.table.setWindowTitle("Store") self.table.setStyleSheet("color:white") self.table.resize(300, 250) self.table.setFont(self.tableFont) self.table.setSortingEnabled(2) #self.table.resizeColumnsToContents() self.table.setRowCount(len(al)) self.table.setColumnCount(len(self.cols)) self.table.setHorizontalHeaderLabels(self.cols) self.table.setContextMenuPolicy(Qt.CustomContextMenu) self.table.customContextMenuRequested.connect(self.handleHeaderMenu) self.table.hideColumn(0) self.table.setSelectionMode(QAbstractItemView.MultiSelection) self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.table.setEditTriggers(QAbstractItemView.NoEditTriggers) i = 0 for q in al: #row id if q['state'] == 1: color = QColor(100, 0, 0) elif q['state'] == 2: color = QColor(100, 100, 0) elif q['state'] == 3: color = QColor(100, 0, 100) elif q['state'] == 4: color = QColor(0, 100, 100) else: color = QColor(0, 50, 150) self.table.setItem(i, 0, QTableWidgetItem(str(q['id']))) self.table.item(i, 0).setBackground(color) self.table.setItem(i, 1, QTableWidgetItem(str(q['itemname']).upper())) self.table.item(i, 1).setBackground(color) self.table.setItem(i, 2, QTableWidgetItem(str(q['quantity']).upper())) self.table.item(i, 2).setBackground(color) try: zamt = str("{:,}".format(float(q['amount']))) except: zamt = '' self.table.setItem(i, 3, QTableWidgetItem(zamt)) self.table.item(i, 3).setBackground(color) try: if len(q['amount']) > 0 and float(q['amount']) > 0: tot = float(q['amount']) * float(q['quantity']) else: tot = 0 except: tot = 0 self.table.setItem(i, 4, QTableWidgetItem(str(tot).upper())) self.table.item(i, 4).setBackground(color) damz = float(q['datepaid']) damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y') self.table.setItem(i, 5, QTableWidgetItem(str(damt))) self.table.item(i, 5).setBackground(color) i += 1 self.table.itemSelectionChanged.connect(self.confirmSelection) self.table.resizeRowsToContents() v_pull_box = QVBoxLayout() self.h1_pull_box.addWidget(self.table) v_pull_box.addLayout(h_pull_box) v_pull_box.addLayout(self.h1_pull_box) h2_pull_box = QHBoxLayout() h2_pull_box.addWidget(self.pb1) h2_pull_box.addWidget(self.pb3) h2_pull_box.addWidget(self.pb6) v_pull_box.addLayout(h2_pull_box) groupBox3 = QGroupBox() groupBox3.setLayout(hbo) groupBox2.setLayout(v_pull_box) grid = QGridLayout() grid.addWidget(groupBox1, 0, 0) grid.addWidget(groupBox2, 0, 1, 2, 1) grid.addWidget(groupBox3, 1, 0) self.setLayout(grid) self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click()) self.connect(self.pb1, SIGNAL("clicked()"), lambda: self.button_editshow()) self.connect(self.pb2, SIGNAL("clicked()"), lambda: self.button_close(self)) self.connect(self.pb3, SIGNAL("clicked()"), lambda: self.button_delete()) self.connect(self.pb4, SIGNAL("clicked()"), lambda: self.button_reset()) self.connect(self.pb5, SIGNAL("clicked()"), lambda: self.button_edit()) self.connect(self.pb6, SIGNAL("clicked()"), lambda: self.button_clear()) #self.connect(self.pull_btn, SIGNAL("clicked()"), lambda x =1: self.reloadTable(x)) self.setWindowTitle(self.pagetitle) def stateReciept(self): self.amountText.show() self.amountData.show() self.tellerText.show() self.tellerData.show() self.tellerText.setText('Reciept No.') self.periodText.hide() self.periodData.hide() self.personText.setText('Recieved By:') self.personData.setPlaceholderText('Fullname or department') self.borrowedText.hide() self.borrowedData.hide() self.reloadTable(1) def stateIssue(self): self.amountText.hide() self.amountData.hide() self.tellerText.show() self.tellerData.show() self.tellerText.setText('Issue No.') self.periodText.hide() self.periodData.hide() self.personText.setText('Issued to:') self.personData.setPlaceholderText('Fullname or department issued to') self.borrowedText.hide() self.borrowedData.hide() self.reloadTable(2) def stateDamage(self): self.amountText.hide() self.amountData.hide() self.tellerText.hide() self.tellerData.hide() self.periodText.hide() self.periodData.hide() self.personText.setText('Reported By:') self.personData.setPlaceholderText('Fullname or department') self.borrowedText.hide() self.borrowedData.hide() self.reloadTable(3) def stateBorrowed(self): self.amountText.hide() self.amountData.hide() self.tellerText.hide() self.tellerData.hide() self.periodText.show() self.periodData.show() self.personText.setText('Given to:') self.personData.setPlaceholderText( 'Fullname or department borrowed to') self.borrowedText.hide() self.borrowedData.hide() self.reloadTable(4) def stateReturned(self): self.amountText.hide() self.amountData.hide() self.tellerText.hide() self.tellerData.hide() self.periodText.hide() self.periodData.hide() self.personText.setText('Returned By:') self.personData.setPlaceholderText( 'Fullname or department borrowed to') self.borrowedText.show() self.borrowedData.show() self.reloadBorrowed() self.reloadTable(5) def changeStates(self): self.getQuantity() if self.r1.isChecked(): self.stateReciept() elif self.r2.isChecked(): self.stateIssue() elif self.r3.isChecked(): self.stateDamage() elif self.r4.isChecked(): self.stateBorrowed() elif self.r5.isChecked(): self.stateReturned() def handleHeaderMenu(self, pos): print('column(%d)' % self.table.horizontalHeader().logicalIndexAt(pos)) menu = QMenu() menu.addAction('Add') menu.addAction('Delete') menu.exec_(QCursor.pos()) def pullGroupStore(self): cn = Db() arr = cn.selectn('datas', '', '', {"pubID": 23, "active": 0}) return arr def pullStore(self, a): cn = Db() arr = cn.selectn('datas', '', '', {"subID": a}) return arr def pullUnit(self): cn = Db() arr = cn.selectn('datas', '', '', {"pubID": 20, "active": 0}) return arr def pullStoreData(self, a=None): st_date = self.fromData.date().toPyDate() en_date = self.toData.date().toPyDate() st_date = time.mktime(st_date.timetuple()) en_date = time.mktime(en_date.timetuple()) db = 'school_stores' + str(self.session) cn = Db() arr = cn.selectStoreDate(db, st_date, en_date, a) return arr def mySelectTable(self): ''' get the selected rpws in a table returns list or row ids ''' sels = self.table.selectedIndexes() sels = self.table.selectionModel().selectedRows() park = [] park1 = [] for j in sels: park.append(j.row()) for i in set(park): selected = self.table.item(i, 0).text() park1.append(selected) return park1 def editRow(self, a): _session = self.session g = Db() db = 'school_stores' + str(_session) data = g.selectn(db, '', 1, {'id': a}) if len(data) > 0: try: amt = float(data['amount']) qty = float(data['quantity']) if amt > 0 and qty > 0: cost = amt * qty else: cost = 0 except: cost = 0 amt = 0 qty = 0 if data['state'] == 1: self.r1.setChecked(True) elif data['state'] == 2: self.r2.setChecked(True) elif data['state'] == 3: self.r3.setChecked(True) elif data['state'] == 4: self.r4.setChecked(True) elif data['state'] == 5: self.r5.setChecked(True) self.amountData.setText(str(cost)) self.descriptionData.clear() self.descriptionData.insertPlainText(str(data['description'])) self.tellerData.setText(str(data['teller'])) self.periodData.setText(str(data['period'])) self.personData.setText(str(data['person'])) self.quantityData.setText(str(qty)) stID = self.hold_store.keys()[self.hold_store.values().index( data['itemID'])] self.storeData.setCurrentIndex(stID) def reloadBorrowed(self): self.getQuantity() _store = self.hold_store[self.storeData.currentIndex()] _session = self.session g = Db() db = 'school_stores' + str(_session) data = g.selectn(db, '', '', {'itemID': _store, 'state': 4}) fig = 0 self.borrowedData.clear() self.hold_borrowed = {} i = 0 for a in data: ret = g.selectStoreReturned(db, a['id']) if ret: retu = ret['qty'] else: retu = 0 fig = float(a['quantity']) - float(retu) damz = float(a['datepaid']) if float(fig) > 0: self.hold_borrowed[i] = a['id'] damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y') tex = str(damt) + " " + str( a['person']).upper() + " (" + str(fig).upper() + ")" self.borrowedData.addItem(tex) i += 1 def reloadStore(self): self.getQuantity() cat = self.hold_storeGroup[self.storeGroupData.currentIndex()] store = self.pullStore(cat) self.storeData.clear() self.hold_store = {} i = 0 for a in store: self.hold_store[i] = a['id'] tex = str(a['name']).upper() self.storeData.addItem(tex) i += 1 def getQuantity(self): if self.storeData.currentIndex() > -1: s = self.hold_store[self.storeData.currentIndex()] _session = self.session g = Db() db = 'school_stores' + str(_session) fi = g.selectStoreQuantity(db, s) remain = 0 arr = {} for a in fi: arr[a['state']] = a['qty'] if 1 in arr: re = arr[1] else: re = 0 if 2 in arr: isu = arr[2] else: isu = 0 if 3 in arr: dam = arr[3] else: dam = 0 if 4 in arr: bor = arr[4] else: bor = 0 if 5 in arr: ret = arr[5] else: ret = 0 borrowed = float(bor) - float(ret) issued = float(isu) + float(borrowed) + float(dam) remain = float(re) - float(issued) self.quantityText.setText('QTY: ' + str(remain)) if remain == 0 and (self.r2.isChecked() or self.r3.isChecked() or self.r4.isChecked()): self.quantityData.setEnabled(False) else: self.quantityData.setEnabled(True) return remain def reloadTable(self, a): self.getQuantity() if not a == 0: data = self.pullStoreData(a) else: data = self.pullStoreData() self.table.close() self.table = QTableWidget() header = self.table.horizontalHeader() header.setResizeMode(QHeaderView.ResizeToContents) header.setStretchLastSection(True) header.setStyleSheet(self.tableHeaderStyle) vheader = self.table.verticalHeader() vheader.setStyleSheet(self.tableHeaderStyle) # Body self.table.setWindowTitle("Stores") self.table.setStyleSheet("color:white") self.table.resize(300, 250) self.table.setFont(self.tableFont) self.table.setSortingEnabled(2) self.table.resizeColumnsToContents() self.table.setRowCount(len(data)) self.table.setColumnCount(len(self.cols)) self.table.setHorizontalHeaderLabels(self.cols) self.table.setContextMenuPolicy(Qt.CustomContextMenu) self.table.customContextMenuRequested.connect(self.handleHeaderMenu) self.table.hideColumn(0) self.table.setSelectionMode(QAbstractItemView.MultiSelection) self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.table.setEditTriggers(QAbstractItemView.NoEditTriggers) i = 0 for q in data: #row id if q['state'] == 1: color = QColor(100, 0, 0) elif q['state'] == 2: color = QColor(100, 100, 0) elif q['state'] == 3: color = QColor(100, 0, 100) elif q['state'] == 4: color = QColor(0, 100, 100) else: color = QColor(0, 50, 150) self.table.setItem(i, 0, QTableWidgetItem(str(q['id']))) self.table.item(i, 0).setBackground(color) self.table.setItem(i, 1, QTableWidgetItem(str(q['itemname']).upper())) self.table.item(i, 1).setBackground(color) self.table.setItem(i, 2, QTableWidgetItem(str(q['quantity']).upper())) self.table.item(i, 2).setBackground(color) try: zamt = str("{:,}".format(float(q['amount']))) except: zamt = '' self.table.setItem(i, 3, QTableWidgetItem(zamt)) self.table.item(i, 3).setBackground(color) try: if len(q['amount']) > 0 and float(q['amount']) > 0: tot = float(q['amount']) * float(q['quantity']) else: tot = 0 except: tot = 0 self.table.setItem(i, 4, QTableWidgetItem(str(tot).upper())) self.table.item(i, 4).setBackground(color) damz = float(q['datepaid']) damt = datetime.utcfromtimestamp(damz).strftime('%d-%m-%Y') self.table.setItem(i, 5, QTableWidgetItem(str(damt))) self.table.item(i, 5).setBackground(color) i += 1 self.table.itemSelectionChanged.connect(self.confirmSelection) self.table.resizeRowsToContents() self.h1_pull_box.addWidget(self.table) self.table.show() def pullOnes(self, a, b): cn = Db() arr = cn.selectn(a, '', 1, {'id': b}) return arr def confirmSelection(self): item = self.mySelectTable() if len(item) == 1: self.pb1.setEnabled(True) self.pb3.setEnabled(True) self.pb6.setEnabled(True) elif len(item) > 1: self.pb1.setEnabled(False) self.pb3.setEnabled(True) self.pb6.setEnabled(True) else: self.pb1.setEnabled(False) self.pb3.setEnabled(False) self.pb6.setEnabled(False) def button_close(self, b): b.close() def button_editshow(self): item = self.mySelectTable() self.editRow(item[0]) self.pb.hide() self.pb4.show() self.pb5.show() def button_delete(self): item = self.mySelectTable() _session = self.session g = Db() db = 'school_stores' + str(_session) for j in item: g.delete(db, {'id': j}) self.reloadTable(1) def button_edit(self): _session = self.session _amounts = self.amountData.text() _teller = self.tellerData.text() _quantity = self.quantityData.text() _person = self.personData.text() _period = self.periodData.text() _date = self.dateData.date().toPyDate() _date = time.mktime(_date.timetuple()) _description = self.descriptionData.toPlainText() _store = self.hold_store[self.storeData.currentIndex()] _borrowed = self.hold_borrowed[self.borrowedData.currentIndex()] arr = {} #recieved if self.r1.isChecked() and _amounts and not ( _amounts == 0) and int(_store) > 0 and int(_quantity) > 0: _amount = float(_amounts) / float(_quantity) arr['amount'] = _amount arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['teller'] = _teller arr['quantity'] = _quantity arr['person'] = _person arr['state'] = 1 #issued elif self.r2.isChecked() and int(_store) > 0 and int(_quantity) > 0: _amount = float(_amounts) / float(_quantity) arr['amount'] = _amount arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['teller'] = _teller arr['quantity'] = _quantity arr['person'] = _person arr['state'] = 2 #damaged elif self.r3.isChecked() and int(_store) > 0 and int(_quantity) > 0: arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['teller'] = _teller arr['quantity'] = _quantity arr['person'] = _person arr['state'] = 3 elif self.r4.isChecked() and int(_store) > 0 and int(_quantity) > 0: arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['quantity'] = _quantity arr['person'] = _person arr['period'] = _period arr['state'] = 4 elif self.r5.isChecked() and int(_store) > 0 and int(_quantity) > 0: _borrowed = self.hold_borrowed[self.borrowedData.currentIndex()] arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['quantity'] = _quantity arr['person'] = _person arr['period'] = _period arr['active'] = _borrowed arr['state'] = 5 ups = {} ups['id'] = self.editID if int(self.editID) > 0 and len(arr) > 0: db = 'school_stores' + str(_session) g = Db() g.update(db, arr, ups) if int(self.editID) > 0: self.button_reset() def button_reset(self): self.getQuantity() self.reloadTable(1) self.amountData.setText('') self.descriptionData.clear() self.tellerData.setText('') self.personData.setText('') self.periodData.setText('') self.quantityData.setText('') self.pb4.hide() self.pb5.hide() self.pb.show() self.editID = 0 self.button_clear() self.confirmSelection() self.reloadBorrowed() def button_clear(self): self.table.selectionModel().clearSelection() def button_click(self): _session = self.session _amounts = self.amountData.text() _teller = self.tellerData.text() _quantity = self.quantityData.text() _person = self.personData.text() _period = self.periodData.text() _date = self.dateData.date().toPyDate() _date = time.mktime(_date.timetuple()) _description = self.descriptionData.toPlainText() _store = self.hold_store[self.storeData.currentIndex()] arr = {} #recieved if self.r1.isChecked() and _amounts and not ( _amounts == 0) and int(_store) > 0 and int(_quantity) > 0: _amount = float(_amounts) / float(_quantity) arr['amount'] = _amount arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['teller'] = _teller arr['quantity'] = _quantity arr['person'] = _person arr['state'] = 1 #issued elif self.r2.isChecked() and _amounts and not ( _amounts == 0) and int(_store) > 0 and int(_quantity) > 0: _amount = float(_amounts) / float(_quantity) arr['amount'] = _amount arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['teller'] = _teller arr['quantity'] = _quantity arr['person'] = _person arr['state'] = 2 #damaged elif self.r3.isChecked() and int(_store) > 0 and int( float(_quantity)) > 0: arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['teller'] = _teller arr['quantity'] = _quantity arr['person'] = _person arr['state'] = 3 elif self.r4.isChecked() and int(_store) > 0 and int( float(_quantity)) > 0: arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['quantity'] = _quantity arr['person'] = _person arr['period'] = _period arr['state'] = 4 elif self.r5.isChecked() and int(_store) > 0 and int( float(_quantity)) > 0 and self.borrowedData.currentIndex() > 0: _borrowed = self.hold_borrowed[self.borrowedData.currentIndex()] arr['datepaid'] = _date arr['description'] = _description arr['itemID'] = _store arr['quantity'] = _quantity arr['person'] = _person arr['period'] = _period arr['active'] = _borrowed arr['state'] = 5 if len(arr) > 0: db = 'school_stores' + str(_session) g = Db() ins = g.insert(db, arr) if int(ins) > 0: self.button_reset()
def view(self): """create view and import layers""" layer = QgsMapLayerRegistry.instance().mapLayer(self.current_layers[0]) uri = QgsDataSourceURI(layer.source()) mtch = re.match(r'(.+)_([^_]+)_rev_(head|\d+)', uri.schema()) schema = mtch.group(1) assert (schema) dlg = QDialog() layout = QVBoxLayout(dlg) button_box = QDialogButtonBox(dlg) button_box.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) button_box.accepted.connect(dlg.accept) button_box.rejected.connect(dlg.reject) user_msg1 = QgsMessageBar(dlg) user_msg1.pushInfo( "Select:", "one [many] for single [multiple] " "revisions. Fetching may take time.") pcur = versioning_base.Db(psycopg2.connect(self.pg_conn_info())) pcur.execute("SELECT rev, commit_msg, branch, date, author " "FROM " + schema + ".revisions") revs = pcur.fetchall() pcur.close() tblw = QTableWidget(dlg) tblw.setRowCount(len(revs)) tblw.setColumnCount(6) tblw.setSortingEnabled(True) tblw.setHorizontalHeaderLabels([ 'Select', 'Revision', 'Commit Message', 'Branch', 'Date', 'Author' ]) tblw.verticalHeader().setVisible(False) for i, rev in enumerate(revs): for j, item in enumerate(rev): chkBoxItem = QTableWidgetItem() chkBoxItem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) chkBoxItem.setCheckState(Qt.Unchecked) tblw.setItem(i, 0, chkBoxItem) tblw.setItem(i, j + 1, QTableWidgetItem(str(item))) layout.addWidget(user_msg1) layout.addWidget(tblw) layout.addWidget(button_box) dlg.resize(650, 300) if not dlg.exec_(): return rows = set() revision_number_list = [] for i in range(len(revs)): if tblw.item(i, 0).checkState(): print "Revision " + str(i + 1) + " will be fetched" revision_number_list.append(i + 1) rows.add(tblw.item(i, 0).row()) progressMessageBar = self.iface.messageBar().createMessage( "Querying " "the database for revision(s) " + str(revision_number_list)) progress = QProgressBar() progress.setMaximum(len(rows)) progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) self.iface.messageBar().pushWidget(progressMessageBar, self.iface.messageBar().INFO) progress.setValue(0) for i, row in enumerate(rows): progress.setValue(i + 1) branch = revs[row][2] rev = revs[row][0] versioning_base.add_revision_view(uri.connectionInfo(), schema, branch, rev) grp_name = branch + ' revision ' + str(rev) grp_idx = self.iface.legendInterface().addGroup(grp_name) for layer_id in reversed(self.current_layers): layer = QgsMapLayerRegistry.instance().mapLayer(layer_id) new_uri = QgsDataSourceURI(layer.source()) new_uri.setDataSource( schema + '_' + branch + '_rev_' + str(rev), new_uri.table(), new_uri.geometryColumn(), new_uri.sql(), new_uri.keyColumn()) display_name = QgsMapLayerRegistry.instance().mapLayer( layer_id).name() src = new_uri.uri().replace('()', '') new_layer = self.iface.addVectorLayer(src, display_name, 'postgres') self.iface.legendInterface().moveLayer(new_layer, grp_idx) self.iface.messageBar().clearWidgets()
class ActionEditorDialog(QWidget): # Redefine the tr() function for this class. def tr(self, text): return qApp.translate("ActionEditorDialog", text) def __init__(self, actions, parent=None): super(ActionEditorDialog, self).__init__(parent) self.actions = actions help = QLabel(translate("Shortcut Settings", '<b>Double click a cell in the Shortcut Column' \ ' to <br />modify the key sequence.</b>')) self.actionTable = QTableWidget(self) self.actionTable.setSelectionBehavior(QTableWidget.SelectRows) self.actionTable.setEditTriggers(QTableWidget.DoubleClicked) self.actionTable.setColumnCount(2) self.actionTable.setHorizontalHeaderLabels( [translate("Shortcut Settings", "Description"), translate("Shortcut Settings", "Shortcut")] ) self.actionTable.horizontalHeader().setStretchLastSection(True) self.actionTable.verticalHeader().hide() self.actionTable.setItemDelegate(ActionEditorDelegate(self)) self.connect(self.actionTable, SIGNAL("cellChanged(int, int)"), self.validateAction) row = 0 for action in self.actions: if action.text().isEmpty(): continue self.actionTable.insertRow(self.actionTable.rowCount()) item = QTableWidgetItem() item.setText(action.text()) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) self.actionTable.setItem(row, 0, item) item = QTableWidgetItem() item.setText(action.shortcut().toString()) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable) item.oldShortcutText = item.text() self.actionTable.setItem(row, 1, item) row += 1 self.actionTable.resizeColumnsToContents() mainLayout = QVBoxLayout() mainLayout.addWidget(help) mainLayout.setMargin(8) mainLayout.setSpacing(8) mainLayout.addWidget(self.actionTable) self.setLayout(mainLayout) self._model = self.actionTable.model() self._model.edited = False self.actionTable.model().edited = False self.setWindowTitle(translate("Shortcut Settings", "Edit Shortcuts")) def applySettings(self, control=None): if not self._model.edited: return row = 0 for action in self.actions: if not action.text().isEmpty(): action.setText(self.actionTable.item(row, 0).text()) action.setShortcut(QKeySequence(self.actionTable.item(row, 1).text())) row += 1 self.saveSettings(self.actions) self._model.edited = False def _loadSettings(self, actions): cparser = PuddleConfig(os.path.join(CONFIGDIR, 'user_shortcuts')) for action in actions: shortcut = cparser.get('shortcuts', unicode(action.text()), '') if shortcut: action.setShortcut(QKeySequence(shortcut)) _loadSettings = classmethod(_loadSettings) def saveSettings(self, actions): cparser = PuddleConfig(os.path.join(CONFIGDIR, 'user_shortcuts')) for action in actions: shortcut = unicode(action.shortcut().toString()) cparser.set('shortcuts', unicode(action.text()), shortcut) saveSettings = classmethod(saveSettings) def validateAction(self, row, column): if column != 1: return item = self.actionTable.item(row, column) shortcutText = QKeySequence(item.text()).toString() thisRow = self.actionTable.row(item) if not shortcutText.isEmpty(): for row in range(self.actionTable.rowCount()): if row == thisRow: continue other = self.actionTable.item(row, 1) if other.text() == shortcutText: other.setText(item.oldShortcutText) break item.setText(shortcutText) item.oldShortcutText = shortcutText self.actionTable.resizeColumnToContents(1)
class KeywordTable(HelpedWidget): """Shows a table of key/value pairs. The data structure expected and sent to the getter and setter is a dictionary of values.""" def __init__(self, model, table_label="", help_link=""): HelpedWidget.__init__(self, table_label, help_link) self.table = QTableWidget(self) self.table.setColumnCount(2) self.setColumnHeaders() self.table.verticalHeader().setHidden(True) self.table.setColumnWidth(0, 150) self.table.horizontalHeader().setStretchLastSection(True) self.table.setMinimumHeight(110) self.table.setSelectionMode(QAbstractItemView.SingleSelection) self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.addWidget(self.table) self.addWidget(AddRemoveWidget(self.addItem, self.removeItem)) self.connect(self.table, SIGNAL('cellChanged(int,int)'), self.tableChanged) assert isinstance(model, DictionaryModelMixin) self.model = model model.observable().attach(DictionaryModelMixin.DICTIONARY_CHANGED_EVENT, self.modelChanged) self.modelChanged() def setColumnHeaders(self, keyword_name="Keyword", value_name="Value"): self.headers = [keyword_name, value_name] self.table.setHorizontalHeaderLabels(self.headers) def addItem(self): """Called by the add button to insert a new keyword""" title = "New %s" % self.headers[0] description = "Enter new %s:" % self.headers[0] (new_keyword, ok) = QInputDialog.getText(self, title, description, QLineEdit.Normal) if ok: new_keyword = str(new_keyword).strip() self.model.addKey(new_keyword) def removeItem(self): """Called by the remove button to remove a selected keyword""" current_row = self.table.currentRow() if current_row >= 0: do_delete = QMessageBox.question(self, "Delete row?", "Are you sure you want to delete the key/value pair?", QMessageBox.Yes | QMessageBox.No ) if do_delete: key_item = self.table.item(current_row, 0) if key_item is not None: key = str(key_item.text()).strip() self.model.removeKey(key) def tableChanged(self, row, column): """Called whenever the contents of a cell changes.""" key_item = self.table.item(row, 0) if key_item is not None: key = str(key_item.text()).strip() value_item = self.table.item(row, 1) if value_item is not None: value = str(value_item.text()).strip() self.model.setValueForKey(key, value) def modelChanged(self): """Retrieves data from the model and inserts it into the table.""" values = self.model.getDictionary() blocked = self.table.blockSignals(True) for row in reversed(range(self.table.rowCount())): self.table.removeRow(row) row = 0 for key in values: key_item = QTableWidgetItem(str(key)) key_item.setFlags(key_item.flags() ^ Qt.ItemIsEditable) value_item = QTableWidgetItem(str(values[key])) self.table.insertRow(row) self.table.setItem(row, 0, key_item) self.table.setItem(row, 1, value_item) row += 1 self.table.blockSignals(blocked)
class ViewTableForm(QWidget): def __init__(self, visualization, parent_widget=None): QWidget.__init__(self, parent_widget) self.inGui = False self.widgetLayout = QVBoxLayout(self) self.tableWidget = QTableWidget(self) self.tableWidget.setObjectName("tableWidget") size = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.tableWidget.setSizePolicy(size) self.widgetLayout.addWidget(self.tableWidget) self.tabIcon = QIcon(":/Images/Images/map.png") self.tabLabel = visualization.table_name self.load_table(visualization=visualization) def load_table(self, visualization, limit=10000): storage = StorageFactory().get_storage( type='%s_storage' % visualization.output_type, storage_location=visualization.storage_location) table_data = storage.load_table(table_name=visualization.table_name) try: primary_keys = visualization.indicators[0].primary_keys except: primary_keys = [] keys = primary_keys + [ key for key in table_data.keys() if key not in primary_keys ] num_rows = min(len(table_data[keys[0]]), limit) num_cols = len(keys) self.tableWidget.clear() self.tableWidget.setColumnCount(num_cols) self.tableWidget.setRowCount(num_rows) j = 0 for key in keys: col = QTableWidgetItem() col.setText(QString(key)) self.tableWidget.setHorizontalHeaderItem(j, col) j += 1 self.tableWidget.resizeColumnsToContents() order = sorted(enumerate(table_data[keys[0]]), lambda (i, v), (j, v2): int(v * 100) - int(v2 * 100)) for i, (idx, v) in enumerate(order): row = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(i, row) j = 0 for key in keys: item = QTableWidgetItem() item.setText(QString(str(table_data[key][idx]))) self.tableWidget.setItem(i, j, item) j += 1 if i > limit: msg = 'The table %s has been truncated to %i rows because of memory limitations.' % ( visualization.table_name, limit) detailed_msg = '<qt>To view the full results, open the following file:<br><br><small>%s</small></qt>' % visualization.get_file_path( ) MessageBox.warning(mainwindow=self, text=msg, detailed_text=detailed_msg) break #self.tableWidget.resizeRowsToContents() def removeElement(self): return True
def view(self): """create view and import layers""" layer = QgsMapLayerRegistry.instance().mapLayer( self.current_layers[0] ) uri = QgsDataSourceURI(layer.source()) mtch = re.match(r'(.+)_([^_]+)_rev_(head|\d+)', uri.schema()) schema = mtch.group(1) assert(schema) dlg = QDialog() layout = QVBoxLayout(dlg) button_box = QDialogButtonBox(dlg) button_box.setStandardButtons( QDialogButtonBox.Cancel|QDialogButtonBox.Ok) button_box.accepted.connect(dlg.accept) button_box.rejected.connect(dlg.reject) user_msg1 = QgsMessageBar(dlg) user_msg1.pushInfo("Select:", "one [many] for single [multiple] " "revisions. Fetching may take time.") pcur = versioning_base.Db( psycopg2.connect(self.pg_conn_info()) ) pcur.execute("SELECT rev, commit_msg, branch, date, author " "FROM "+schema+".revisions") revs = pcur.fetchall() pcur.close() tblw = QTableWidget( dlg ) tblw.setRowCount(len(revs)) tblw.setColumnCount(6) tblw.setSortingEnabled(True) tblw.setHorizontalHeaderLabels(['Select','Revision', 'Commit Message', 'Branch', 'Date', 'Author']) tblw.verticalHeader().setVisible(False) for i, rev in enumerate(revs): for j, item in enumerate(rev): chkBoxItem = QTableWidgetItem() chkBoxItem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) chkBoxItem.setCheckState(Qt.Unchecked) tblw.setItem(i, 0, chkBoxItem) tblw.setItem(i, j+1, QTableWidgetItem( str(item) )) layout.addWidget( user_msg1 ) layout.addWidget( tblw ) layout.addWidget( button_box ) dlg.resize( 650, 300 ) if not dlg.exec_() : return rows = set() revision_number_list = [] for i in range(len(revs)): if tblw.item(i,0).checkState(): print "Revision "+ str(i + 1) +" will be fetched" revision_number_list.append(i + 1) rows.add(tblw.item(i,0).row()) progressMessageBar = self.iface.messageBar().createMessage("Querying " "the database for revision(s) "+str(revision_number_list)) progress = QProgressBar() progress.setMaximum(len(rows)) progress.setAlignment(Qt.AlignLeft|Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) self.iface.messageBar().pushWidget(progressMessageBar, self.iface.messageBar().INFO) progress.setValue(0) for i, row in enumerate(rows): progress.setValue(i+1) branch = revs[row][2] rev = revs[row][0] versioning_base.add_revision_view(uri.connectionInfo(), schema, branch, rev ) grp_name = branch+' revision '+str(rev) grp_idx = self.iface.legendInterface().addGroup( grp_name ) for layer_id in reversed(self.current_layers): layer = QgsMapLayerRegistry.instance().mapLayer(layer_id) new_uri = QgsDataSourceURI(layer.source()) new_uri.setDataSource(schema+'_'+branch+'_rev_'+str(rev), new_uri.table(), new_uri.geometryColumn(), new_uri.sql(), new_uri.keyColumn()) display_name = QgsMapLayerRegistry.instance().mapLayer(layer_id).name() src = new_uri.uri().replace('()','') new_layer = self.iface.addVectorLayer( src, display_name, 'postgres') self.iface.legendInterface().moveLayer( new_layer, grp_idx) self.iface.messageBar().clearWidgets()
class TemplateWindow(QMainWindow): def __init__(self, params_pipe, number_pipe, templates_pipe, spikes_pipe, probe_path=None, screen_resolution=None): QMainWindow.__init__(self) # Receive parameters. params = params_pipe[0].recv() self.probe = load_probe(probe_path) self._nb_samples = params['nb_samples'] self._sampling_rate = params['sampling_rate'] self._display_list = [] self._params = { 'nb_samples': self._nb_samples, 'sampling_rate': self._sampling_rate, 'time': { 'min': 10.0, # ms 'max': 100.0, # ms 'init': 100.0, # ms }, 'voltage': { 'min': -200, # µV 'max': 20e+1, # µV 'init': 50.0, # µV }, 'templates': self._display_list } self._canvas_mea = MEACanvas(probe_path=probe_path, params=self._params) self._canvas_template = TemplateCanvas(probe_path=probe_path, params=self._params) self._canvas_rate = RateCanvas(probe_path=probe_path, params=self._params) self._canvas_isi = ISICanvas(probe_path=probe_path, params=self._params) self.cells = Cells({}) self._nb_buffer = 0 # TODO ISI self.isi_bin_width, self.isi_x_max = 2, 25.0 canvas_template_widget = self._canvas_template.native canvas_mea = self._canvas_mea.native canvas_rate = self._canvas_rate.native canvas_isi = self._canvas_isi.native # Create controls widgets. label_time = QLabel() label_time.setText(u"time") label_time_unit = QLabel() label_time_unit.setText(u"ms") self._dsp_time = QDoubleSpinBox() self._dsp_time.setMinimum(self._params['time']['min']) self._dsp_time.setMaximum(self._params['time']['max']) self._dsp_time.setValue(self._params['time']['init']) self._dsp_time.valueChanged.connect(self._on_time_changed) label_voltage = QLabel() label_voltage.setText(u"voltage") label_voltage_unit = QLabel() label_voltage_unit.setText(u"µV") self._dsp_voltage = QDoubleSpinBox() self._dsp_voltage.setMinimum(self._params['voltage']['min']) self._dsp_voltage.setMaximum(self._params['voltage']['max']) self._dsp_voltage.setValue(self._params['voltage']['init']) self._dsp_voltage.valueChanged.connect(self._on_voltage_changed) label_binsize = QLabel() label_binsize.setText(u"Bin size") label_binsize_unit = QLabel() label_binsize_unit.setText(u"second") self._dsp_binsize = QDoubleSpinBox() self._dsp_binsize.setRange(0.1, 10) self._dsp_binsize.setSingleStep(0.1) self.bin_size = 1 self._dsp_binsize.setValue(self.bin_size) self._dsp_binsize.valueChanged.connect(self._on_binsize_changed) label_zoomrates = QLabel() label_zoomrates.setText(u'Zoom rates') self._zoom_rates = QDoubleSpinBox() self._zoom_rates.setRange(1, 50) self._zoom_rates.setSingleStep(0.1) self._zoom_rates.setValue(1) self._zoom_rates.valueChanged.connect(self._on_zoomrates_changed) label_time_window = QLabel() label_time_window.setText(u'Time window rates') label_time_window_unit = QLabel() label_time_window_unit.setText(u'second') self._dsp_tw_rate = QDoubleSpinBox() self._dsp_tw_rate.setRange(1, 50) self._dsp_tw_rate.setSingleStep(self.bin_size) self._dsp_tw_rate.setValue(50 * self.bin_size) self._dsp_tw_rate.valueChanged.connect(self._on_time_window_changed) label_tw_from_start = QLabel() label_tw_from_start.setText('Time scale from start') self._tw_from_start = QCheckBox() self._tw_from_start.setChecked(True) self._selection_templates = QTableWidget() self._selection_templates.setSelectionMode( QAbstractItemView.ExtendedSelection ) self._selection_templates.setColumnCount(3) self._selection_templates.setVerticalHeaderLabels(['Nb template', 'Channel', 'Amplitude']) self._selection_templates.insertRow(0) self._selection_templates.setItem(0, 0, QTableWidgetItem('Nb template')) self._selection_templates.setItem(0, 1, QTableWidgetItem('Channel')) self._selection_templates.setItem(0, 2, QTableWidgetItem('Amplitude')) # self._selection_channels.setGeometry(QtCore.QRect(10, 10, 211, 291)) # for i in range(self.nb_templates): # numRows = self.tableWidget.rowCount() # self.tableWidget.insertRow(numRows) # item = QTableWidgetItem("Template %i" % i) # self._selection_templates.addItem(item) # self._selection_templates.item(i).setSelected(False) spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) # Create controls grid. grid = QGridLayout() # # Add time row. grid.addWidget(label_time, 0, 0) grid.addWidget(self._dsp_time, 0, 1) grid.addWidget(label_time_unit, 0, 2) # # Add voltage row. grid.addWidget(label_voltage, 1, 0) grid.addWidget(self._dsp_voltage, 1, 1) grid.addWidget(label_voltage_unit, 1, 2) # # Add binsize row. grid.addWidget(label_binsize, 2, 0) grid.addWidget(self._dsp_binsize, 2, 1) grid.addWidget(label_binsize_unit, 2, 2) # # Add zoom rate grid.addWidget(label_zoomrates, 3, 0) grid.addWidget(self._zoom_rates, 3, 1) # Add a double checkbox for time window grid.addWidget(label_time_window, 4, 0) grid.addWidget(self._dsp_tw_rate, 4, 1) grid.addWidget(label_time_window_unit, 4, 2) ## Add checkbox to display the rates from start grid.addWidget(label_tw_from_start, 5, 0) grid.addWidget(self._tw_from_start, 5, 1) # # Add spacer. grid.addItem(spacer) # # Create info group. controls_group = QGroupBox() controls_group.setLayout(grid) # Create info grid. templates_grid = QGridLayout() # # Add Channel selection # grid.addWidget(label_selection, 3, 0) templates_grid.addWidget(self._selection_templates, 0, 1) def add_template(): items = self._selection_templates.selectedItems() self._display_list = [] for i in range(len(items)): self._display_list.append(i) self._on_templates_changed() # self._selection_templates.itemClicked.connect(add_template) # Template selection signals self._selection_templates.itemSelectionChanged.connect(lambda: self.selected_templates( self.nb_templates)) # Checkbox to display all the rates self._tw_from_start.stateChanged.connect(self.time_window_rate_full) # self._selection_templates.itemPressed(0, 1).connect(self.sort_template()) # # Add spacer. templates_grid.addItem(spacer) # Create controls group. templates_group = QGroupBox() templates_group.setLayout(templates_grid) # # Create controls dock. templates_dock = QDockWidget() templates_dock.setWidget(templates_group) templates_dock.setWindowTitle("Channels selection") # # Create controls dock. control_dock = QDockWidget() control_dock.setWidget(controls_group) control_dock.setWindowTitle("Controls") # Create info widgets. label_time = QLabel() label_time.setText(u"time") self._label_time_value = QLineEdit() self._label_time_value.setText(u"0") self._label_time_value.setReadOnly(True) self._label_time_value.setAlignment(Qt.AlignRight) label_time_unit = QLabel() label_time_unit.setText(u"s") info_buffer_label = QLabel() info_buffer_label.setText(u"buffer") self._info_buffer_value_label = QLineEdit() self._info_buffer_value_label.setText(u"0") self._info_buffer_value_label.setReadOnly(True) self._info_buffer_value_label.setAlignment(Qt.AlignRight) info_buffer_unit_label = QLabel() info_buffer_unit_label.setText(u"") info_probe_label = QLabel() info_probe_label.setText(u"probe") info_probe_value_label = QLineEdit() info_probe_value_label.setText(u"{}".format(probe_path)) info_probe_value_label.setReadOnly(True) # TODO place the following info in another grid? info_probe_unit_label = QLabel() info_probe_unit_label.setText(u"") info_spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) # Create info grid. info_grid = QGridLayout() # # Time row. info_grid.addWidget(label_time, 0, 0) info_grid.addWidget(self._label_time_value, 0, 1) info_grid.addWidget(label_time_unit, 0, 2) # # Buffer row. info_grid.addWidget(info_buffer_label, 1, 0) info_grid.addWidget(self._info_buffer_value_label, 1, 1) info_grid.addWidget(info_buffer_unit_label, 1, 2) # # Probe row. info_grid.addWidget(info_probe_label, 2, 0) info_grid.addWidget(info_probe_value_label, 2, 1) info_grid.addWidget(info_probe_unit_label, 2, 2) # # Spacer. info_grid.addItem(info_spacer) # Create info group. info_group = QGroupBox() info_group.setLayout(info_grid) # Create info dock. info_dock = QDockWidget() info_dock.setWidget(info_group) info_dock.setWindowTitle("Info") # Create thread. thread = Thread(number_pipe, templates_pipe, spikes_pipe) thread.number_signal.connect(self._number_callback) thread.reception_signal.connect(self._reception_callback) thread.start() # Add dockable windows. self.addDockWidget(Qt.LeftDockWidgetArea, control_dock) self.addDockWidget(Qt.LeftDockWidgetArea, info_dock) self.addDockWidget(Qt.LeftDockWidgetArea, templates_dock) # Add Grid Layout for canvas canvas_grid = QGridLayout() group_canv_temp = QDockWidget() group_canv_temp.setWidget(canvas_template_widget) group_canv_mea = QDockWidget() group_canv_mea.setWidget(canvas_mea) group_canv_rate = QDockWidget() group_canv_rate.setWidget(canvas_rate) group_canv_isi = QDockWidget() group_canv_isi.setWidget(canvas_isi) canvas_grid.addWidget(group_canv_temp, 0, 0) canvas_grid.addWidget(group_canv_mea, 0, 1) canvas_grid.addWidget(group_canv_rate, 1, 1) canvas_grid.addWidget(group_canv_isi, 1, 0) canvas_group = QGroupBox() canvas_group.setLayout(canvas_grid) # Set central widget. self.setCentralWidget(canvas_group) # Set window size. if screen_resolution is not None: screen_width = screen_resolution.width() screen_height = screen_resolution.height() self.resize(screen_width, screen_height) # Set window title. self.setWindowTitle("SpyKING Circus ORT - Read 'n' Qt display") print(" ") # TODO remove? @property def nb_templates(self): return len(self.cells) def _number_callback(self, number): self._nb_buffer = float(number) text = u"{}".format(number) self._info_buffer_value_label.setText(text) text = u"{:8.3f}".format(self._nb_buffer * float(self._nb_samples) / self._sampling_rate) self._label_time_value.setText(text) return def _reception_callback(self, templates, spikes): bar = None if templates is not None: bar = [] for i in range(len(templates)): mask = spikes['templates'] == i template = load_template_from_dict(templates[i], self.probe) new_cell = Cell(template, Train([]), Amplitude([], [])) self.cells.append(new_cell) self._selection_templates.insertRow(self.nb_templates) bar += [template.center_of_mass(self.probe)] channel = template.channel amplitude = template.peak_amplitude() # self._selection_templates.setItem(self.nb_templates, 0, QTableWidgetItem("Template %d" %self.nb_templates)) # self._selection_templates.setItem(self.nb_templates, 1, QTableWidgetItem(str(bar))) self._selection_templates.setItem(self.nb_templates, 0, QTableWidgetItem(str(self.nb_templates))) self._selection_templates.setItem(self.nb_templates, 1, QTableWidgetItem(str(channel))) self._selection_templates.setItem(self.nb_templates, 2, QTableWidgetItem(str(amplitude))) # item = QListWidgetItem("Template %i" % self.nb_templates) # self._selection_templates.addItem(item) # self._selection_templates.item(i).setSelected(False) # self.nb_templates += 1 # print(bar.shape, bar) if spikes is not None: self.cells.add_spikes(spikes['spike_times'], spikes['amplitudes'], spikes['templates']) self.cells.set_t_max(self._nb_samples * self._nb_buffer / self._sampling_rate) to_display = self.cells.rate(self.bin_size) self._canvas_template.on_reception(templates, self.nb_templates) self._canvas_mea.on_reception_bary(bar, self.nb_templates) # TODO Cells rate self._canvas_rate.on_reception_rates(self.cells.rate(self.bin_size)) # TODO : ISI If we want to display the ISI also # isi = self.cells.interspike_interval_histogram(self.isi_bin_width, self.isi_x_max=25.0) isi = self.cells.interspike_interval_histogram(self.isi_bin_width, self.isi_x_max) self._canvas_isi.on_reception_isi(isi) return def _on_time_changed(self): time = self._dsp_time.value() self._canvas_template.set_time(time) self._dsp_tw_rate.setRange(1, int(time)) return def _on_binsize_changed(self): time = self._dsp_binsize.value() self.bin_size = time self._dsp_tw_rate.setSingleStep(self.bin_size) return def _on_zoomrates_changed(self): zoom_value = self._zoom_rates.value() self._canvas_rate.zoom_rates(zoom_value) return def _on_voltage_changed(self): voltage = self._dsp_voltage.value() self._canvas_template.set_voltage(voltage) return def _on_peaks_display(self): value = self._display_peaks.isChecked() self._canvas_template.show_peaks(value) return def _on_templates_changed(self): self._canvas_template.set_templates(self._display_list) return def selected_templates(self, max_templates): list_templates = [] list_channels = [] for i in range(max_templates + 1): if i != 0 and \ self._selection_templates.item(i, 0).isSelected() and \ self._selection_templates.item(i, 1).isSelected() and \ self._selection_templates.item(i, 2).isSelected(): list_templates.append(i - 1) list_channels.append(int(self._selection_templates.item(i, 1).text())) self._canvas_template.selected_templates(list_templates) self._canvas_mea.selected_channels(list_channels) self._canvas_mea.selected_templates(list_templates) self._canvas_rate.selected_cells(list_templates) self._canvas_isi.selected_cells(list_templates) return def time_window_rate_full(self): value = self._tw_from_start.isChecked() self._canvas_rate.time_window_full(value) return def _on_time_window_changed(self): tw_value = self._dsp_tw_rate.value() self._canvas_rate.time_window_value(tw_value, self.bin_size) return
class NewRelationDialog(QDialog): def __init__(self, parent=None): QDialog.__init__(self, parent) self.setWindowTitle(self.tr("Nueva Relación")) vbox = QVBoxLayout(self) hbox = QHBoxLayout() self._line_relation_name = QLineEdit() hbox.addWidget(QLabel(self.tr("Nombre:"))) hbox.addWidget(self._line_relation_name) vbox.addLayout(hbox) vbox.addWidget(QLabel( self.tr("La primera fila corresponde a los campos"))) hbox = QHBoxLayout() btn_add_column = QPushButton(self.tr("Agregar Columna")) hbox.addWidget(btn_add_column) btn_add_tuple = QPushButton(self.tr("Agregar Tupla")) hbox.addWidget(btn_add_tuple) btn_remove_column = QPushButton(self.tr("Eliminar Columna")) hbox.addWidget(btn_remove_column) btn_remove_tuple = QPushButton(self.tr("Eliminar Tupla")) hbox.addWidget(btn_remove_tuple) vbox.addLayout(hbox) self._table = QTableWidget() vbox.addWidget(self._table) self._table.setRowCount(1) self._table.setColumnCount(2) self._table.setItem(0, 0, QTableWidgetItem("Campo 1")) self._table.setItem(0, 1, QTableWidgetItem("Campo 2")) hbox = QHBoxLayout() hbox.addItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) btn_ok = QPushButton(self.tr("Aceptar")) hbox.addWidget(btn_ok) btn_cancel = QPushButton(self.tr("Cancelar")) hbox.addWidget(btn_cancel) vbox.addLayout(hbox) # Connections self.connect(btn_add_column, SIGNAL("clicked()"), self.__add_column) self.connect(btn_remove_column, SIGNAL("clicked()"), self.__remove_column) self.connect(btn_add_tuple, SIGNAL("clicked()"), self.__add_tuple) self.connect(btn_remove_tuple, SIGNAL("clicked()"), self.__remove_tuple) self.connect(btn_ok, SIGNAL("clicked()"), self.__create_table) self.connect(btn_cancel, SIGNAL("clicked()"), self.close) def __add_column(self): columns = self._table.columnCount() self._table.insertColumn(columns) def __remove_column(self): current = self._table.currentColumn() self._table.removeColumn(current) def __add_tuple(self): tuples = self._table.rowCount() self._table.insertRow(tuples) def __remove_tuple(self): current = self._table.currentRow() self._table.removeRow(current) def __create_table(self): name = self._line_relation_name.text() rows = self._table.rowCount() columns = self._table.columnCount() rel = relation.Relation() fields = [self._table.item(0, i).text() for i in range(columns)] rel.fields = fields data = {} for row in range(1, rows): reg = [] for column in range(columns): reg.append(self._table.item(row, column).text()) data[row, column] = self._table.item(row, column).text() rel.insert(reg) table_widget = Pireal.get_service("container").table_widget table_widget.add_table(rows - 1, columns, name, data) #table_widget.relations[name] = rel self.close()
class ViewTableForm(QWidget): def __init__(self, visualization, parent_widget = None): QWidget.__init__(self, parent_widget) self.inGui = False self.widgetLayout = QVBoxLayout(self) self.tableWidget = QTableWidget(self) self.tableWidget.setObjectName("tableWidget") size = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.tableWidget.setSizePolicy(size) self.widgetLayout.addWidget(self.tableWidget) self.tabIcon = QIcon(":/Images/Images/map.png") self.tabLabel = visualization.table_name self.load_table(visualization = visualization) def load_table(self, visualization, limit = 10000): storage = StorageFactory().get_storage( type = '%s_storage'%visualization.output_type, storage_location = visualization.storage_location) table_data = storage.load_table( table_name = visualization.table_name) try: primary_keys = visualization.indicators[0].primary_keys except: primary_keys = [] keys = primary_keys + [key for key in table_data.keys() if key not in primary_keys] num_rows = min(len(table_data[keys[0]]), limit) num_cols = len(keys) self.tableWidget.clear() self.tableWidget.setColumnCount(num_cols) self.tableWidget.setRowCount(num_rows) j = 0 for key in keys: col = QTableWidgetItem() col.setText(QString(key)) self.tableWidget.setHorizontalHeaderItem(j,col) j += 1 self.tableWidget.resizeColumnsToContents() order = sorted(enumerate(table_data[keys[0]]), lambda (i,v),(j,v2): int(v*100)-int(v2*100)) for i, (idx,v) in enumerate(order): row = QTableWidgetItem() self.tableWidget.setVerticalHeaderItem(i,row) j = 0 for key in keys: item = QTableWidgetItem() item.setText(QString(str(table_data[key][idx]))) self.tableWidget.setItem(i,j,item) j += 1 if i > limit: msg = 'The table %s has been truncated to %i rows because of memory limitations.'%(visualization.table_name,limit) detailed_msg = '<qt>To view the full results, open the following file:<br><br><small>%s</small></qt>'%visualization.get_file_path() MessageBox.warning(mainwindow = self, text = msg, detailed_text = detailed_msg) break #self.tableWidget.resizeRowsToContents() def removeElement(self): return True
def initUI(self): exitAction = QtGui.QAction('Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(self.close) # infoAction = QtGui.q # infoAction.triggered.connect() menubar = self.menuBar() fileMenu = menubar.addMenu('File') fileMenu.addAction(exitAction) fileMenu = menubar.addMenu('Help'); # fileMenu.addAction(infoAction) # toolbar = self.addToolBar('Exit') # toolbar.addAction(exitAction) # Button # redb = QtGui.QPushButton('Play', self) # redb.move(10, 22) # Slider sld = QtGui.QSlider(QtCore.Qt.Horizontal, self) # Do not accept keyboard shortcuts to focus sld.setFocusPolicy(QtCore.Qt.NoFocus) # Initial X, Initial Y, Width, Height sld.setGeometry(10, 210, 500, 15) sld.valueChanged[int].connect(self.updateSlider) # Table of songs table = QTableWidget(self) table.setColumnCount(4) table.setRowCount(4) table.setHorizontalHeaderLabels(['Title', 'Artist', 'Album', 'Year']) table.move(10, 30) table.resize(580, 170) table.setColumnWidth(0, 250) table.setColumnWidth(1, 130) table.setColumnWidth(2, 120) table.setColumnWidth(3, 60) # Play self.playb = QtGui.QLabel(self) # Todo: Change icon self.playb.setPixmap(QtGui.QPixmap('D:\Documents\Pictures\L.jpg')) self.playb.setGeometry(15, 235, 40, 40) self.playb.setScaledContents(True) self.connect(self.playb, QtCore.SIGNAL("clicked()"), self.play) self.playb.pressed.connect(self.play) # Pause self.label = QtGui.QLabel(self) # Todo: Change icon self.label.setPixmap(QtGui.QPixmap('D:\Documents\Pictures\L.jpg')) self.label.setGeometry(65, 235, 40, 40) self.label.setScaledContents(True) # Timer self.timer = QtGui.QLabel(self) # Todo: Change icon self.timer.setText("00:00") self.timer.setStyleSheet("font: 15pt;") self.timer.setGeometry(520, 195, 60, 40) self.timer.setScaledContents(True) # Initial X, Initial Y, Width, Height self.setGeometry(100, 100, 600, 300) self.setWindowTitle('Music Player') # Todo: Change icon path self.setWindowIcon(QtGui.QIcon('D:\Documents\Pictures\L.jpg')) self.show()
class typicalWindow(QtGui.QMainWindow): def __init__(self, parent=None): super(typicalWindow, self).__init__(parent) # QtGui.QMainWindow.__init__(self) #window self.setWindowTitle(winTitle) self.central_widget=QWidget(self) self.setCentralWidget(self.central_widget) self.masterLayout=QGridLayout(self.central_widget) self.masterLayout.setAlignment(QtCore.Qt.AlignTop) #mainlayout self.vertical_order_layout=QtGui.QBoxLayout(2) self.vertical_order_layout.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignVCenter) self.masterLayout.addLayout(self.vertical_order_layout, 0,0,1,1) self.topDivideLayout=QGridLayout() self.botDivideLayout=QGridLayout() self.upper_layout=QGridLayout() self.topDivideLayout.addLayout(self.upper_layout, 0,0,1,1) self.lower_layout=QGridLayout() self.lower_layout.setAlignment(QtCore.Qt.AlignTop) self.botDivideLayout.addLayout(self.lower_layout, 0,0,1,1) self.midLayout=QGridLayout() self.midLayout.setAlignment(QtCore.Qt.AlignTop) self.base_layout=QGridLayout() self.base_layout.setAlignment(QtCore.Qt.AlignTop) self.botDivideLayout.addLayout(self.base_layout, 4,0,1,1) #sshFile=open(os.path.join(__location__, styleSheetFile+".stylesheet"), 'r') #self.styleData=sshFile.read() #sshFile.close #self.setStyleSheet(self.styleData) self.top=QtGui.QFrame(self) self.top.setFrameShape(QtGui.QFrame.StyledPanel) self.top.setLayout(self.topDivideLayout) self.bottom=QtGui.QFrame(self) self.bottom.setFrameShape(QtGui.QFrame.StyledPanel) self.bottom.setLayout(self.botDivideLayout) self.splitPlane=QtGui.QSplitter(QtCore.Qt.Vertical) self.splitPlane.addWidget(self.top) self.splitPlane.addWidget(self.bottom) self.splitPlane.setSizes([650, 650]) self.vertical_order_layout.addWidget(self.splitPlane) #layouts self.window_layer_00=QGridLayout() self.upper_layout.addLayout(self.window_layer_00, 0,0,1,1) self.window_layer_01=QGridLayout() self.upper_layout.addLayout(self.window_layer_01,1,0,1,1) self.window_layer_02=QGridLayout() self.upper_layout.addLayout(self.window_layer_02, 2,0,1,1) self.window_layer_03=QGridLayout() self.upper_layout.addLayout(self.window_layer_03,3,0,1,1) self.window_layer_04=QGridLayout() self.upper_layout.addLayout(self.window_layer_04, 4,0,1,1) self.window_layer_05=QGridLayout() self.upper_layout.addLayout(self.window_layer_05,5,0,1,1) self.window_layer_06=QGridLayout() self.midLayout.addLayout(self.window_layer_06, 6,0,1,1) self.frame_layout=QGridLayout() self.frame_layout.setAlignment(QtCore.Qt.AlignTop) self.lower_layout.addLayout(self.frame_layout, 0,0,1,1) self.frameWidget=QtGui.QGridLayout() self.frameWidget.setContentsMargins(5,10,5,10) self.frameOverride=QtGui.QFrame() self.frameOverride.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;") self.frameOverride.setFixedHeight(100) self.frame_layout.addLayout(self.frameWidget, 0,0,1,1) self.frame_layout.addWidget(self.frameOverride, 0,0,1,1) self.frame_title_layout=QGridLayout() self.frameWidget.addLayout(self.frame_title_layout, 0,0,1,1) self.frame_radio_layout=QGridLayout() self.frameWidget.addLayout(self.frame_radio_layout, 1,0,1,1) self.frame_btn_layout=QGridLayout() self.frameWidget.addLayout(self.frame_btn_layout, 2,0,1,1) self.btm_btn_layout=QtGui.QGridLayout() self.btm_btn_layout.setAlignment(QtCore.Qt.AlignTop) self.btm_btn_layout.setContentsMargins(5,10,5,10) self.wbFrame=QtGui.QFrame() self.wbFrame.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;") self.btm_over_layout=QtGui.QGridLayout() self.btm_over_layout.setAlignment(QtCore.Qt.AlignTop) self.btm_over_layout.addLayout(self.btm_btn_layout, 0,0,1,1) self.btm_over_layout.addWidget(self.wbFrame, 0,0,1,1) self.pkt_layout= QGridLayout() self.pkt_layout.setAlignment(QtCore.Qt.AlignTop) self.pkt_widget=QGridLayout() self.pkt_widget.setContentsMargins(5,5,5,5) self.pkt_frame=QFrame() self.pkt_frame.setMinimumWidth(650) self.pkt_frame.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;") self.base_layout.addLayout(self.pkt_layout, 0,0,1,1) self.wndw_layer_pkt=QtGui.QGridLayout() self.wndw_layer_pkt.setAlignment(QtCore.Qt.AlignTop) self.pkt_widget.addLayout(self.wndw_layer_pkt, 0,0,1,1) self.park_btn_pkt=QtGui.QBoxLayout(2) self.park_btn_pkt.setAlignment(QtCore.Qt.AlignTop) self.park_btn_pkt.setContentsMargins(5,2,5,8) self.wndw_layer_pkt.addLayout(self.park_btn_pkt, 0,0,1,1) self.park_frame=QtGui.QFrame() self.park_frame.setStyleSheet("background-color: #434343; border-style: solid; border-width: 2px; border-color:#434343;border-radius:8px;") #widgets self.drop_lbl_01=QLabel() self.drop_lbl_01.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) self.drop_lbl_01.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.window_layer_01.addWidget(self.drop_lbl_01, 0,0,1,1) self.drop_01=QComboBox() self.window_layer_01.addWidget(self.drop_01, 0,1,1,1) self.drop_01.addItems(prjFileName) self.drop_01.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.drop_01.customContextMenuRequested.connect(self.onRightClick) # self.drop_01.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) # self.connect(self.drop_lbl_01, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick) self.drop_lbl_02=QLabel() self.drop_lbl_02.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) self.drop_lbl_02.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.window_layer_01.addWidget(self.drop_lbl_02, 0,2,1,1) self.drop_02=QComboBox() self.window_layer_01.addWidget(self.drop_02, 0,3,1,1) # QtCore.QObject.connect(self.drop_02, SIGNAL("currentIndexChanged(QString)"), # self.on_drop_01_changed) self.drop_02.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.connect(self.drop_lbl_01, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick) QtCore.QObject.connect(self.drop_01, SIGNAL("currentIndexChanged(QString)"), self.on_drop_01_changed) self.button_01=QPushButton("Set") self.button_01.setToolTip("set") self.connect(self.button_01, SIGNAL('clicked()'), self.listCreate) self.window_layer_01.addWidget(self.button_01, 0,4,1,1) self.button_02=QPushButton("Set2") self.button_02.setToolTip("set2") self.connect(self.button_02, SIGNAL('clicked()'), self.connectButton01) self.window_layer_01.addWidget(self.button_02, 0,5,1,1) self.drop_lbl_03=QLabel() self.drop_lbl_03.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter) self.drop_lbl_03.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.window_layer_02.addWidget(self.drop_lbl_03, 0,0,1,1) self.drop_03=QComboBox() self.window_layer_02.addWidget(self.drop_03, 0,1,1,1) # QtCore.QObject.connect(self.drop_03, SIGNAL("currentIndexChanged(QString)"), # self.on_drop_01_changed) self.drop_03.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.connect(self.drop_03, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick) self.button_03=QPushButton("button_03") self.button_03.setToolTip("button_03") self.connect(self.button_03, SIGNAL('clicked()'), self.connectButton01) self.window_layer_02.addWidget(self.button_03, 0,2,1,1) self.button_04=QPushButton("button_04") self.button_04.setToolTip("button_04") self.connect(self.button_04, SIGNAL('clicked()'), self.connectButton01) self.window_layer_02.addWidget(self.button_04, 0,3,1,1) self.button_05=QPushButton("button_05") self.button_05.setToolTip("button_05") self.connect(self.button_05, SIGNAL('clicked()'), self.connectButton01) self.window_layer_02.addWidget(self.button_05, 0,4,1,1) self.drop_04=QComboBox() self.window_layer_04.addWidget(self.drop_04, 0,2,1,1) # QtCore.QObject.connect(self.drop_04, SIGNAL("currentIndexChanged(QString)"), # self.on_drop_01_changed) self.drop_04.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.connect(self.drop_04, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick) self.list_frame=QFrame() self.list_frame.setStyleSheet("color: rgb"+str(buttonColoursDict.get("red"))) self.list_layout=QHBoxLayout() self.list_frame.setLayout(self.list_layout) self.drop_list_builder_05=QComboBox() self.drop_list_builder_05.addItems(get_a_play_list) QtCore.QObject.connect(self.drop_list_builder_05, SIGNAL("currentIndexChanged(QString)"), self.build) self.drop_list_builder_05.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.connect(self.drop_list_builder_05, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick) self.list_layout.addWidget(self.drop_list_builder_05) self.window_layer_04.addWidget(self.list_frame, 0,3,1,1) self.drop_list_06=QComboBox() # QtCore.QObject.connect(self.drop_list_06, SIGNAL("currentIndexChanged(QString)"),self.load) self.drop_list_06.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.connect(self.drop_list_06, SIGNAL("customContextMenuRequested(QPoint)"), self.onRightClick) #if len(pres)<1: #self.drop_list_06.setEnabled(0) #else: #self.drop_list_06.setEnabled(1) self.drop_list_06.addItems(alist2) self.list_layout.addWidget(self.drop_list_06) self.type_list_drop=QComboBox() self.type_list_drop.addItems(typesOfStuffInList) QtCore.QObject.connect(self.type_list_drop, SIGNAL("currentIndexChanged(QString)"), self.on_drop_01_changed) self.window_layer_04.addWidget(self.type_list_drop, 0,5,1,1) self.button_06=QPushButton("button_06") self.button_06.setToolTip("button_06") self.connect(self.button_06, SIGNAL('clicked()'), self.connectButton01) self.window_layer_04.addWidget(self.button_06, 0,6,0,1) headers = ('Name', 'Date', 'Path') self.listWidg = QTableWidget(1, 3) # self.listWidg.setSelectionMode(QtGui.QAbstractItemView.SingleSelection) # self.listWidg.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) # self.listWidg.cellPressed.connect(self.clicked) # self.listWidg=QTableWidget(0, 3) self.listWidg.setHorizontalHeaderLabels(headers) # tableWidget=self.listWidg self.listWidg.setEditTriggers(QAbstractItemView.DoubleClicked | QAbstractItemView.SelectedClicked) col1, col2, col3= 240, 160, 500 self.listWidg.setColumnWidth(0, col1) self.listWidg.setColumnWidth(1, col2) self.listWidg.setColumnWidth(2, col3) self.listWidg.setSelectionBehavior(QAbstractItemView.SelectRows) self.listWidg.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.listWidg.customContextMenuRequested.connect(self.RightClick) # self.listWidg.setSelectionMode(QtGui.QAbstractItemView.MultiSelection) self.connect(self.listWidg, SIGNAL("itemClicked(QTableWidgetItem *)"), self.clicked) self.connect(self.listWidg, SIGNAL("itemDoubleClicked(QTableWidgetItem *)"), self.dclicked) self.window_layer_05.addWidget(self.listWidg, 0,2,1,1) self.status_lbl=QLabel() self.status_lbl.setStyleSheet('background-color:transparent') self.status_lbl.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter) self.frame_title_layout.addWidget(self.status_lbl, 0,2,1,1) self.spaceHold=QLabel() self.spaceHold.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.spaceHold.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter) self.frame_title_layout.addWidget(self.spaceHold, 0,0,1,1) self.checkbox=QCheckBox("add") self.checkbox.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") # self.checkbox.setContentsMargins(5,0,0,0) self.checkbox.setChecked(1) self.frame_title_layout.addWidget(self.checkbox, 0,1,1,1) self.radiobox=QGridLayout() self.radio=QRadioButton("radio") self.radio.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.radio.setChecked(1) self.radiobox.addWidget(self.radio, 0,0,1,1) self.newradio=QRadioButton("newradio") self.newradio.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.radiobox.addWidget(self.newradio, 0,2,1,1) self.frame_len_layout=QGridLayout() self.frame_len_layout.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter) #self.frame_title_layout.addWidget(self.frame_len_layout, 1,3,1,1) self.spaceHold=QLabel() self.spaceHold.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.spaceHold.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter) self.frame_title_layout.addWidget(self.spaceHold, 0,3,1,1) self.over=QRadioButton("over") self.over.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.radiobox.addWidget(self.over, 1,1,1,1) self.head_lbl=QLabel("from") self.head_lbl.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.radiobox.addWidget(self.head_lbl, 1, 4,1,1) self.head_field=QTextEdit("") self.head_field.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.radiobox.addWidget(self.head_field, 1, 5,1,1) self.toe_lbl=QLabel("til") self.toe_lbl.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.radiobox.addWidget(self.toe_lbl, 1, 6,1,1) self.toe_field=QTextEdit("") self.toe_field.setStyleSheet("color: #b1b1b1; background-color: rgba(255,255,255,0);") self.radiobox.addWidget(self.toe_field, 1, 7,1,1) self.fieldBox=QLineEdit() self.fieldBox.setVisible(0) self.fieldBox.setText(defaultText) self.play_in_rv_button=QPushButton("play in RV") self.connect(self.play_in_rv_button, SIGNAL('clicked()'), self.play_in_rv) self.frame_btn_layout.addWidget(self.play_in_rv_button, 0,0,0,1) self.look_btn=QPushButton("compare") self.connect(self.look_btn, SIGNAL('clicked()'), self.compare_in_rv) self.frame_btn_layout.addWidget(self.look_btn, 0,1, 0,1) # self.link_btn=QPushButton("link") # self.connect(self.link_btn, SIGNAL('clicked()'), self.play_in_rv) # self.frame_btn_layout.addWidget(self.link_btn, 0,2,1,1) self.create_btn=QPushButton("Publish") self.connect(self.create_btn, SIGNAL('clicked()'), self.pub_to_shotgun) self.frame_btn_layout.addWidget(self.create_btn, 0,3, 1,1) self.pocketTitle=QPushButton("title") self.pocketTitle.setObjectName('label') #self.pocketTitle.setStyleSheet("QPushButton#label{font-weight:500; color: rgb"str(buttonColorDict).get("yello"))+"; button-color: rgba(255,255,255,0); font-size: 10pt; border-width: 0px; font-style: bold;}") self.connect(self.pocketTitle, SIGNAL('clicked()'), self.send) self.connect(self.pocketTitle, SIGNAL('customContextMenuRequested(QPoint)'), lambda: self.send()) self.park_btn_pkt.addWidget(self.pocketTitle) self.a_btn=QPushButton("a_btn") #self.a_btn.setStyleSheet("background-color: rgb"str(buttonColorDict).get("yello"))) self.connect(self.a_btn, SIGNAL('clicked()'), self.play_in_rv) self.park_btn_pkt.addWidget(self.a_btn) self.card_menu=QMenu("card") self.card_menuBar=self.menuBar() self.card_menuBar.addMenu(self.card_menu) self.park_btn_pkt.addWidget(self.card_menuBar) buttonGrp.append(self.card_menuBar) self.card_btn=QToolButton() self.card_btn.setPopupMode(QToolButton.MenuButtonPopup) self.card_btn.setMenu(self.card_menu) self.card_special_btn=QPushButton("card special") self.connect(self.card_special_btn, SIGNAL('clicked()'), self.card_special_callup) action=QtGui.QWidgetAction(self.card_btn) action.setDefaultWidget(self.card_special_btn) self.card_btn.menu().addAction(action) self.B_card_btn=QToolButton() self.B_card_btn.setPopupMode(QToolButton.MenuButtonPopup) self.B_card_btn.setMenu(self.card_menu) self.B_card_special_btn=QPushButton("card special") self.connect(self.B_card_special_btn, SIGNAL('clicked()'),self.B_card_special_callup) action=QtGui.QWidgetAction(self.B_card_btn) action.setDefaultWidget(self.B_card_special_btn) self.B_card_btn.menu().addAction(action) self.start_window() def start_window(self): # self.connectButton01 print PROJECT print SCENE print SHOT index = self.drop_01.findText(SCENE, QtCore.Qt.MatchFixedString) self.drop_01.setCurrentIndex(index) self.get_scene() index2 = self.drop_02.findText(SHOT, QtCore.Qt.MatchFixedString) self.drop_02.setCurrentIndex(index2) self.listCreate() def buttonToggle(self): get_a_layout=self.park_btn_pkt get_size=get_a_layout.getContentsMargine() if get_size==(0,0,0,0): self.setvisible() else: self.setinvisible() def setinvisible(self): for each in buttonGrp: each.setVisible(0) self.park_btn_pkt.setContentsMargine(0,0,0,0) def setvisible(self): for each in buttonGrp: each.setVisible(1) self.park_btn_pkt.setContentsMargine(5,8,5,8) def get_scene(self): scene=self.drop_01 scene=scene.currentText() getPath='/jobs/'+PROJECT+'/'+scene get_items=os.listdir(getPath) get_items=sorted(get_items) # get_items=set(get_items) # get_items=sorted(get_items) self.get_shot(get_items) def get_shot(self, get_items): getDropScene=self.drop_02 getDropScene.clear() getDropScene.addItems(get_items) def onRightClick(self): scene=self.drop_01 scene=scene.currentText() path='/jobs/'+PROJECT+'/'+scene+"/" self.launch_folder(path) def launch_folder(self, path): # command="xdg-open '%s'"%path command="dolphin '%s'"%path subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) def on_drop_01_changed(self): self.get_scene() newcol1=self.listWidg.columnWidth(0) newcol2=self.listWidg.columnWidth(1) newcol3=self.listWidg.columnWidth(2) if newcol1==0: col1, col2, col3= 240, 160, 500 else: col1, col2, col3= newcol1, newcol2, newcol3 # findproject=self.drop_01 self.listWidg.clear() self.status_lbl.clear() # self.listCreate() # self.makeList(listpath, newUser, self.listWidg, model, stat_lab, listtype) # self.drop_03.addItems(get_items) # model, countdata, listArray =self.get_listStuff() # if self.on_drop_01=="item1": # buildListPath=pathList.get("listpathtype").replace(getUser, newUser) # self.makeList(listpath, newUser, self.listWidg, model, stat_lab, listtype) # elif self.on_drop_01=="item2": # buildListPath=pathList.get("listpathtype2").replace(getUser, newUser) # self.makeList(listpath, newUser, self.listWidg, model, stat_lab, listtype) def clicked(self): print "hi" def dclicked(self): print "hello" def get_listStuff(self): listArray=self.listWidg countdata=listArray.rowCount() model=listArray.model() return model, countdata, listArray def getListWidgetData(self): model, countdata, listArray =self.get_listStuff() dataInListWidget=[] for row in range(model.rowCount()): dataInListWidget.append([]) for column in range(model.columnCount()): index = model.index(row, column) dataInListWidget[row].append(str(model.data(index).toString())) return dataInListWidget, countdata def grab_folder_items(self): directory=rvFolder getstuff=os.listdir(directory) getUser=M_USER (dataInListWidget, countdata)=self.getListWidgetData() # self.listWidg.setRowCount(0) # self.listWidg.setColumnCount(0) try: getFiles=[os.path.join(directory, o) for o in os.listdir(directory) if os.path.isdir(os.path.join(directory, o))] pass except: print "nothing found" return getFile=[(each) for each in getFiles if getpwuid(stat(each).st_uid).pw_name==getUser] getFiles.sort(key=lambda x: os.path.getmtime(x)) fileDict=[] for each in getFiles: statbuf=os.stat(each) timeFormat=time.strftime('%m/%d/%Y', time.gmtime(os.path.getctime(each))) getAccTime=time.ctime(os.path.getmtime(each)) if " " in str(getAccTime): getAccTime=getAccTime.split(" ") getAccTime=getAccTime[1].split(" ")[1] else: getAccTime=getAccTime.split(" ")[3] timeFormat=timeFormat+" "+getAccTime makeDict=(each, timeFormat) fileDict.append(makeDict) count=len(fileDict) fileDict=reversed(fileDict) dictItems=fileDict return fileDict, count def listCreate(self): self.listWidg.setColumnCount(3) fileDict, count=self.grab_folder_items() self.listWidg.setRowCount(count) for row, item in enumerate(fileDict): key=item[0].split('/')[-1] path=item[0] value=item[1] self.listWidg.setItem(row, 0, QTableWidgetItem(key)) self.listWidg.setItem(row, 1, QTableWidgetItem(value)) self.listWidg.setItem(row, 2, QTableWidgetItem(path)) def is_listWid_item_selected(self): listW=self.listWidg (dataInListWidget, countdata)=self.getListWidgetData() get_string_id=[] for index in xrange(countdata): get=listW.item(index, 0).isSelected() if get==True: getObj=listW.item(index, 2).text() getObj=str(getObj) get_string_id.append(getObj) else: get=listW.item(index, 1).isSelected() if get==True: getObj=listW.item(index, 2).text() getObj=str(getObj) get_string_id.append(getObj) else: get=listW.item(index, 2).isSelected() if get==True: getObj=listW.item(index, 2).text() getObj=str(getObj) get_string_id.append(getObj) return get_string_id def build(self): list_build=self.drop_list_builder_05 list_build_function=list_build.currentText() selected_in_list=self.is_listWid_item_selected() allthePaths=('//', '//') allthePathsDic={"firstPath":'//', "secondPath":'//'} #drop_list_builder_05 getlisttype=self.type_list_drop listtype=getlisttype.currentText() if selected_in_list>1: getItems=[(each) for each in selected_in_list] nameToSave=' '.join(getItems) if listtype=="firstPath": suffixAppend="first" path=allthePathsDic.get("firstPath") if listtype=="secondPath": suffixAppend="second" path=allthePathsDic.get("secondPath") compareBucket=[] getitems=[(suffixAppend+":"+each.split("/")[-1]) for each in selected_in_list] name_to_save=' '.join(getitems) if list_build_function==get_a_play_list[1]: prompt="name of list:" getcomment=self.makeBody(prompt) if getComment==None: print "needs name" return else: pass getComment=getComment.replace(' ', '_') #shotList=suffixAppend+"_"+getComment+"storedText.txt" fileBuild=path+shotList copyfilemessage="creating in "+fileBuild replay = QtGui.QMessageBox.question(None, 'Message' ,copyfilemessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: if os.path.isfile(fileBuild)==True: cmessage="create over "+fileBuild replay = QtGui.QMessageBox.question(None, 'Message' ,cmessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: inp=open(fileBuild, "w+") inp.write(name_to_save) inp.close() print "created "+fileBuild else: print "cancelled" return else: inp=open(fileBuild, "w+") inp.write(name_to_save) inp.close() print "created "+fileBuild else: print "cancelled" return elif list_build_function==get_a_play_list[2]: fileDict, list=self.getAllLists(allthePaths) def getAllLists(self, stuff): fileDict={} for each in stuff: getList, getnamesdic=self.obtain_presets(each) getnames=getnamesdic.keys() for eachp in eachn in map(None, getList, getnames): dictlist={eachn:eachp} fileDict.update(dictlist) return fileDict, getList def obtain_presets(self, morestuff): preset=False format=".txt" getpreset=[os.path.join(dirpath, name) for dirpath, dirnames, files in os.walk(morestuff) for name in files if name.lower().endswith(format)] preset=[(each) for each in getpreset if "storedText" in each] getlistnames={} for each in preset: getName=each.split("/")[-1] nam=getName.split("_") getpletename='_'.join(nam[:-1]) diction={getpletename:nam[0]} getlistnames.update(diction) return preset, getlistnames def makeBody(self, prompt): text, ok=QtGui.QInputDialog.getText(None, 'Intput Dialog', prompt) if ok: project=(str(text)) else: return return project def makeBodyFilled(self, prompt, message): text, ok=QtGui.QInputDialog.getText(None, 'Intput Dialog', prompt, QtGui.QLineEdit.Normal, message) if ok and text: project=(str(text)) else: return return project def load(self): list_load=self.drop_list_06 list_load_function=list_load.currentText() allthePaths=('//', '//') allthePathsDic={"firstPath":'//', "secondPath":'//'} if list_load_function==presetlist[0]: prompt="name of list:" getcomment=self.makeBody(prompt) if getComment==None: print "needs name" return else: pass getComment=getComment.replace(' ', '_') shotList=suffixAppend+"_"+getComment+"storedText.txt" fileBuild=path+shotList copyfilemessage="creating in "+fileBuild replay = QtGui.QMessageBox.question(None, 'Message', copyfilemessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: if os.path.isfile(fileBuild)==True: cmessage="create over "+fileBuild replay = QtGui.QMessageBox.question(None, 'Message' ,cmessage, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: inp=open(fileBuild, "w+") inp.write(name_to_save) inp.close() print "created "+fileBuild else: print "cancelled" return else: inp=open(fileBuild, "w+") inp.write(name_to_save) inp.close() print "created "+fileBuild else: print "cancelled" return elif list_build_function==list_build[2]: fileDict, list=self.getAllLists(allthePaths) def reset_callup(self): allthePaths=('//', '//') allthePathsDic={"firstPath":'//', "secondPath":'//'} getlisttype=self.type_list_drop listtype=getlisttype.currentText() if listtype=="firstPath": directory=allthePathsDic.get("firstPath") getUser=getUser self.directory_for_taking(getUser, directory) def directory_for_taking(self, getUser, directory): model, countdata, listArray =self.get_listStuff() # self.status_lbl def connectButton01(self): print "hi" self.listCreate() def RightClick(self): selected_in_list=self.is_listWid_item_selected() path=str(selected_in_list[0])+"/" # command="xdg-open '%s'"%path self.launch_folder(path) def play_in_rv(self): selected_in_list=self.is_listWid_item_selected() command="rv "+str(selected_in_list[0])+"/*" print "you are running command: "+command subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) def compare_in_rv(self): selected_in_list=self.is_listWid_item_selected() if len(selected_in_list)<2: print "must select more than one object in list" else: command="rv -wipe "+str(selected_in_list[0])+"/* "+str(selected_in_list[1])+"/*" print "you are running command: "+command subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) def pub_to_shotgun(self): selected_in_list=self.is_listWid_item_selected() getPath=selected_in_list[0]+'/'+foldertypeplay+"/" get_items=os.listdir(getPath) getFileName=get_items[0].split(".")[0] print getFileName # getFileName=str(getFileName)+"-"+str(typeplay) # print getFileName format="_jpg" # command='msubmitCmd -p "'+str(selected_in_list[0])+getFileName+'.%04d'+formatEXT+'"'+' -s '+str(startFR)+' -e '+str(endFR)+' -t review -n='+comment+' --task techanim -audio '+audioFile+' -audioOffset 0' command='msubmitCmd -p "'+str(selected_in_list[0])+'/'+typeplay+format+'/'+getFileName+'.%04d'+formatEXT+'"'+' -s '+str(startFR)+' -e '+str(endFR)+' -t review -n="'+comment+'" --task '+DEPT # command="rv "+str(selected_in_list[0])+"/*" print "you are running command: "+command subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) def send(self): print "end" def card_special_callup(self): print "card_special_callup" def Bcard_special_callup(self): print "B_card_special_callup" def B_card_special_callup(self): print "B_card_special_callup"
class NewRelationDialog(QDialog): def __init__(self, parent=None): QDialog.__init__(self, parent) self.setWindowTitle(self.tr("Nueva Relación")) vbox = QVBoxLayout(self) hbox = QHBoxLayout() self._line_relation_name = QLineEdit() hbox.addWidget(QLabel(self.tr("Nombre:"))) hbox.addWidget(self._line_relation_name) vbox.addLayout(hbox) vbox.addWidget(QLabel( self.tr("La primera fila corresponde a los campos"))) hbox = QHBoxLayout() btn_add_column = QPushButton(self.tr("Agregar Columna")) hbox.addWidget(btn_add_column) btn_add_tuple = QPushButton(self.tr("Agregar Tupla")) hbox.addWidget(btn_add_tuple) btn_remove_column = QPushButton(self.tr("Eliminar Columna")) hbox.addWidget(btn_remove_column) btn_remove_tuple = QPushButton(self.tr("Eliminar Tupla")) hbox.addWidget(btn_remove_tuple) vbox.addLayout(hbox) self._table = QTableWidget() vbox.addWidget(self._table) self._table.setRowCount(1) self._table.setColumnCount(2) self._table.setItem(0, 0, QTableWidgetItem("Campo 1")) self._table.setItem(0, 1, QTableWidgetItem("Campo 2")) hbox = QHBoxLayout() hbox.addItem(QSpacerItem(1, 0, QSizePolicy.Expanding)) btn_ok = QPushButton(self.tr("Aceptar")) hbox.addWidget(btn_ok) btn_cancel = QPushButton(self.tr("Cancelar")) hbox.addWidget(btn_cancel) vbox.addLayout(hbox) # Connections self.connect(btn_add_column, SIGNAL("clicked()"), self.__add_column) self.connect(btn_remove_column, SIGNAL("clicked()"), self.__remove_column) self.connect(btn_add_tuple, SIGNAL("clicked()"), self.__add_tuple) self.connect(btn_remove_tuple, SIGNAL("clicked()"), self.__remove_tuple) self.connect(btn_ok, SIGNAL("clicked()"), self.__create_table) self.connect(btn_cancel, SIGNAL("clicked()"), self.close) def __add_column(self): columns = self._table.columnCount() self._table.insertColumn(columns) def __remove_column(self): current = self._table.currentColumn() self._table.removeColumn(current) def __add_tuple(self): tuples = self._table.rowCount() self._table.insertRow(tuples) def __remove_tuple(self): current = self._table.currentRow() self._table.removeRow(current) def __create_table(self): # Name of relation name = self._line_relation_name.text() if not name.strip(): QMessageBox.critical(self, self.tr("Error"), self.tr("Nombre de relación no especificado")) return rows = self._table.rowCount() columns = self._table.columnCount() rel = relation.Relation() # Header of relation fields = [] for i in range(columns): text = self._table.item(0, i).text() if not text.strip(): QMessageBox.critical(self, self.tr("Error"), self.tr("Nombre de campo inválido")) return fields.append(text) rel.fields = fields # Data data = {} for row in range(1, rows): reg = [] for column in range(columns): item = self._table.item(row, column) if item is None or not item.text().strip(): QMessageBox.critical(self, self.tr("Campo vacío"), self.tr("El campo {0}:{1} está " "vacío").format(row + 1, column + 1)) return reg.append(self._table.item(row, column).text()) data[row, column] = self._table.item(row, column).text() rel.insert(reg) # Add table and relation table_widget = Pireal.get_service("container").table_widget table_widget.add_table(rows - 1, columns, name, data, fields) table_widget.relations[name] = rel self.close()
def __init__(self, parent=None): super(Window, self).__init__(parent) self.setWindowTitle("Battmon") # a figure instance to plot on self.figure = Figure() # this is the Canvas Widget that displays the `figure` # it takes the `figure` instance as a parameter to __init__ self.canvas = FigureCanvasQTAgg(self.figure) # this is the Navigation widget # it takes the Canvas widget and a parent self.toolbar = NavigationToolbar(self.canvas, self) # set the layout main_layout = QtGui.QHBoxLayout() graph_layout = QtGui.QVBoxLayout() self.info_layout = QtGui.QVBoxLayout() # sizing policies fixed_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) hpref_policy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) vpref_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) states = get_battery_states() self.battery_widgets = {} for battery in sorted(states.keys()): battinfo_gbox = QtGui.QGroupBox("Battery: " + battery) battinfo_vbox = QtGui.QVBoxLayout() table = QTableWidget() table.setRowCount(len(BATTERY_DATA_FILES)) table.setColumnCount(2) table.verticalHeader().setVisible(False) table.horizontalHeader().setVisible(False) table.horizontalHeader().setResizeMode(QHeaderView.Stretch) table.verticalHeader().setResizeMode(QHeaderView.Stretch) table.setMinimumHeight(50) table.setSizePolicy(vpref_policy) battinfo_vbox.addWidget(table) progress = QtGui.QProgressBar(self) battinfo_vbox.addWidget(progress) progress.setSizePolicy(hpref_policy) progress.setFormat("%v%") self.battery_widgets[battery] = {} self.battery_widgets[battery]["table"] = table self.battery_widgets[battery]["progress"] = progress battinfo_gbox.setSizePolicy(vpref_policy) battinfo_gbox.setLayout(battinfo_vbox) self.info_layout.addWidget(battinfo_gbox) # Checkbox to select fields to graph fields_gbox = QtGui.QGroupBox("Show:") fields_hbox = QtGui.QHBoxLayout() self.capacity = QtGui.QCheckBox("Capacity") self.voltage = QtGui.QCheckBox("Voltage") self.energy = QtGui.QCheckBox("Energy") self.energy.clicked.connect(self.plot) self.voltage.clicked.connect(self.plot) self.capacity.clicked.connect(self.plot) fields_hbox.addWidget(self.capacity) fields_hbox.addWidget(self.energy) fields_hbox.addWidget(self.voltage) fields_gbox.setLayout(fields_hbox) fields_gbox.setSizePolicy(fixed_policy) graph_layout.addWidget(fields_gbox) # Radio buttons to restrict timeframe to graph timeframe_gbox = QtGui.QGroupBox("Time Frame:") timeframe_hbox = QtGui.QHBoxLayout() self.day = QtGui.QRadioButton("Day") self.week = QtGui.QRadioButton("Week") self.month = QtGui.QRadioButton("Month") self.all = QtGui.QRadioButton("All") self.day.clicked.connect(self.plot) self.week.clicked.connect(self.plot) self.month.clicked.connect(self.plot) self.all.clicked.connect(self.plot) timeframe_hbox.addWidget(self.day) timeframe_hbox.addWidget(self.week) timeframe_hbox.addWidget(self.month) timeframe_hbox.addWidget(self.all) timeframe_gbox.setLayout(timeframe_hbox) timeframe_gbox.setSizePolicy(fixed_policy) graph_layout.addWidget(timeframe_gbox) graph_layout.addWidget(self.toolbar) graph_layout.addWidget(self.canvas) main_layout.addLayout(self.info_layout) main_layout.addLayout(graph_layout) main_layout.addWidget(QtGui.QSizeGrip(self), 0, Qt.AlignBottom | Qt.AlignRight) self.setLayout(main_layout) # Default graph is week data self.week.setChecked(True) self.capacity.setChecked(True) self.energy.setChecked(True) self.voltage.setChecked(True) # populate initial data self.update() self.plot()
def _init_layout(self): """ Create the GUI widgets (but leave them empty). """ hostname_combobox = QComboBox(parent=self) self._hostname_combobox = hostname_combobox hostname_combobox.setEditable(True) hostname_combobox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum) for hostname in self._suggested_hostnames: hostname_combobox.addItem(hostname) # EventFilter is installed after everything else is initialized. (See below.) #hostname_combobox.installEventFilter(self) self._connect_button = QPushButton("Connect", parent=self, clicked=self._handle_new_hostname) hostname_layout = QHBoxLayout() hostname_layout.addWidget(hostname_combobox) hostname_layout.addWidget(self._connect_button) hostinfo_table = QTableWidget() hostinfo_table.setColumnCount(len(SERVER_INFO_FIELDS)) hostinfo_table.setHorizontalHeaderLabels(SERVER_INFO_FIELDS) hostinfo_table.horizontalHeader().setVisible(True) hostinfo_table.verticalHeader().setVisible(False) hostinfo_table.setRowCount(1) hostinfo_table.setItem(0, 0, QTableWidgetItem("Placeholder")) hostinfo_table.setVisible(False) hostinfo_table.resizeRowsToContents() hostinfo_table.horizontalHeader().setStretchLastSection(True) table_height = hostinfo_table.verticalHeader().sectionSize( 0) + hostinfo_table.rowHeight(0) hostinfo_table.resize(QSize(hostinfo_table.width(), table_height)) hostinfo_table.setMaximumSize(QSize(1000, table_height)) hostinfo_table.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) host_layout = QVBoxLayout() host_layout.addLayout(hostname_layout) host_layout.addWidget(hostinfo_table) host_groupbox = QGroupBox("DVID Host", parent=self) host_groupbox.setLayout(host_layout) host_groupbox.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) repo_treewidget = QTreeWidget(parent=self) repo_treewidget.setHeaderLabels( TREEVIEW_COLUMNS) # TODO: Add type, shape, axes, etc. repo_treewidget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) repo_treewidget.itemSelectionChanged.connect( self._handle_data_selection) data_layout = QVBoxLayout() data_layout.addWidget(repo_treewidget) data_groupbox = QGroupBox("Data Volumes", parent=self) data_groupbox.setLayout(data_layout) node_listwidget = QListWidget(parent=self) node_listwidget.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) node_listwidget.itemSelectionChanged.connect(self._update_status) node_layout = QVBoxLayout() node_layout.addWidget(node_listwidget) node_groupbox = QGroupBox("Nodes", parent=self) node_groupbox.setLayout(node_layout) new_data_edit = QLineEdit(parent=self) new_data_edit.textEdited.connect(self._update_status) full_url_label = QLabel(parent=self) full_url_label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) text_flags = full_url_label.textInteractionFlags() full_url_label.setTextInteractionFlags(text_flags | Qt.TextSelectableByMouse) new_data_layout = QVBoxLayout() new_data_layout.addWidget(new_data_edit) new_data_groupbox = QGroupBox("New Data Volume", parent=self) new_data_groupbox.setLayout(new_data_layout) new_data_groupbox.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) buttonbox = QDialogButtonBox(Qt.Horizontal, parent=self) buttonbox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonbox.accepted.connect(self.accept) buttonbox.rejected.connect(self.reject) buttonbox.button(QDialogButtonBox.Ok).setEnabled(False) layout = QVBoxLayout() layout.addWidget(host_groupbox) layout.addWidget(data_groupbox) layout.addWidget(node_groupbox) if self._mode == "specify_new": layout.addWidget(new_data_groupbox) else: new_data_groupbox.hide() layout.addWidget(full_url_label) layout.addWidget(buttonbox) # Stretch factors layout.setStretchFactor(data_groupbox, 3) layout.setStretchFactor(node_groupbox, 1) self.setLayout(layout) self.setWindowTitle("Select DVID Volume") self.resize(1000, 1000) # Initially disabled data_groupbox.setEnabled(False) node_groupbox.setEnabled(False) new_data_groupbox.setEnabled(False) # Set tab order self.setTabOrder(hostname_combobox, repo_treewidget) self.setTabOrder(repo_treewidget, node_listwidget) self.setTabOrder(node_listwidget, buttonbox) # Save instance members self._hostinfo_table = hostinfo_table self._data_groupbox = data_groupbox self._node_groupbox = node_groupbox self._new_data_groupbox = new_data_groupbox self._repo_treewidget = repo_treewidget self._node_listwidget = node_listwidget self._new_data_edit = new_data_edit self._full_url_label = full_url_label self._buttonbox = buttonbox # Finally install eventfilter (after everything is initialized) hostname_combobox.installEventFilter(self)
class ImportDataDlg(QDialog): __isJy = False # 数据校验成功的标志 __mlist = [] # 定义一个列表用于保存从excel表中取出的数据 def __init__(self, iface, parent=None, impType=ImpDateType.SITEANDCELL): super(ImportDataDlg, self).__init__() self.iface = iface self.parent = parent self.impType = impType self.initView() def initView(self): if self.impType == ImpDateType.SERVINGCELL: self.setWindowTitle(u'相邻小区数据导入') else: self.setWindowTitle(u'基站和小区数据导入') self.setWindowIcon(QIcon('images/logo.png')) self.resize(620, 480) # 数据表格 self.tableWidget = QTableWidget(self) self.tableWidget.setAlternatingRowColors(True) self.tableWidget.setRowCount(7) # 设置当前Table不能编辑 self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers) # 初始化表格上下文菜单 self.initTableContextMenu() # 初始化表头 self.initTableHeader() # 导入出错列表 self.listWidget = QListWidget(self) # 按钮组 impBtn = QPushButton(u"导入EXCEL表", self) yzBtn = QPushButton(u"数据检验", self) impdateBtn = QPushButton(u"导入数据", self) btnVBox = QVBoxLayout() btnVBox.addWidget(impBtn) btnVBox.addWidget(yzBtn) btnVBox.addWidget(impdateBtn) # 错误列表与按钮组 hBox = QHBoxLayout() hBox.setMargin(20) hBox.addWidget(self.listWidget) hBox.addLayout(btnVBox) self.mbar = QStatusBar(self) self.mbar.showMessage(u'准备就绪...') self.maction = QToolBar(self) self.editAction = QAction(u'编辑', self.maction) self.editAction.setCheckable(True) self.combox = QComboBox(self) self.combox.addItems(HeadsConfig.ImpExcelName) self.maction.addWidget(self.combox) self.maction.addAction(self.editAction) vBox = QVBoxLayout() vBox.addWidget(self.maction) vBox.addWidget(self.tableWidget) vBox.addLayout(hBox) vBox.addWidget(self.mbar) vBox.setStretchFactor(self.tableWidget, 9) vBox.setStretchFactor(hBox, 5) vBox.setStretchFactor(self.mbar, 1) self.setLayout(vBox) QObject.connect(impBtn, SIGNAL('clicked()'), self.impClick) QObject.connect(yzBtn, SIGNAL('clicked()'), self.yzClick) QObject.connect(impdateBtn, SIGNAL('clicked()'), self.impdateClick) QObject.connect(self.editAction, SIGNAL('triggered()'), self.editClick) QObject.connect(self.combox, SIGNAL('currentIndexChanged(int)'), self.comboxChange) self.listWidget.doubleClicked.connect(self.mlistClicked) # self.connect(self.listWidget, SIGNAL("itemDoubleClicked (QListWidgetItem)"), self.mlistClicked) def initTableContextMenu(self): self.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu) self.popMenu = QMenu(self.tableWidget) delAction = QAction(u'删除', self) # 删除 self.popMenu.addAction(delAction) # 设置表格可以双击修改数据 def setEditTriggers(self, isTrigger): if isTrigger: self.tableWidget.setEditTriggers(QAbstractItemView.DoubleClicked) else: self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers) # 提供给外部修改状态栏消息 def setStatusBarMsg(self, msg): self.mbar.showMessage(msg) # 选框改变时,清空当前表格的全部内容,包括表格头 def updateType(self, mtype): self.impType = mtype self.tableWidget.clear() # 清空表格所有内容 self.initTableHeader() # 初始化表格的每个Item def initTable(self, mlist): self.tableWidget.setRowCount(len(mlist)) for (i, v) in enumerate(mlist): for (j, item) in enumerate(v): if type(item) != str: item = unicode(item) if item == None: item = u"" tabItem = QTableWidgetItem(item) tabItem.setTextAlignment(Qt.AlignCenter) self.tableWidget.setItem(i, j, tabItem) # 初始化错误信息列表 def initListView(self, mlist): for iv in mlist: lisItm = QListWidgetItem(self.listWidget) lisItm.setTextColor(Qt.red) lisItm.setData(Qt.UserRole, iv) if isinstance(iv, basestring): # 如果错误信息是一行字符串 lisItm.setText(iv) else: lisItm.setText(u'第' + unicode(str(iv['row'] + 1)) + u'行,第' + unicode(str(iv['col'] + 1)) + u'列:' + iv['msg']) # 初始化Table的头 def initTableHeader(self): self.heads = [] if self.impType == ImpDateType.SITEANDCELL: # 获取当前项目图层的字段名 cell_layer = getLayerByName(u"小区", self.iface) for head in HeadsConfig.SiteANDCellHead: self.heads.append(head) if len(cell_layer.pendingFields()) > 55: for (index, field) in enumerate(cell_layer.pendingFields()): if index > 54: field_name = field.name().strip() self.heads.append(field_name) else: self.heads = HeadsConfig.ServingCellHead self.tableWidget.setColumnCount(len(self.heads)) # 设置表格的列数 for (i, h) in enumerate(self.heads): tabItem = QTableWidgetItem(h) self.tableWidget.setHorizontalHeaderItem(i, tabItem) # 自定义为Table添加Item def addTableItem(self, row, col, content): tabItem = QTableWidgetItem(content) self.tableWidget.setItem(row, col, tabItem) # 修改Item的内容 def editTableItem(self, row, col, content): tabItem = self.tableWidget.item(row, col) tabItem.setText(content) self.tableWidget.setItem(row, col, tabItem) # 从Excel表读取数据(导入Excel表) def impClick(self): fileName = QFileDialog.getOpenFileName(self, u'基站小区数据导入', '/', 'Excel Files (*.xls *.xlsx)') if fileName.strip() != "": self.setStatusBarMsg(u'选择完毕:' + fileName) importData = GetDataFromExcel(fileName, self.impType, self.heads) self.__mlist = [] self.__mlist.extend(importData.getData()) self.tableWidget.clearContents() self.listWidget.clear() self.initTable(self.__mlist) self.setStatusBarMsg(u'数据导入完成...') self.__isJy = False # 导入完数据后,说明需要重新验证数据的正确性 else: QMessageBox.information(self.parent, u"错误", u"请选中文件") # 数据验证按钮点击事件处理 def yzClick(self): if len(self.__mlist) > 0: self.erlist = [] # 定义一个列表用于保存数据验证错误的数据 # 清楚全部的Item if self.listWidget.count() > 0: self.listWidget.clear() # 根据tableWidget更新self.__mlist for (r, items) in enumerate(self.__mlist): for (v, item) in enumerate(self.__mlist[r]): if self.tableWidget.item(r, v).text() == u"": continue else: # 跟据self.__mlist[r][v]数据类型进行比对 if type(self.__mlist[r][v]) == int: if unicode(self.__mlist[r][v]) != ( self.tableWidget.item(r, v).text()): self.__mlist[r][v] = int( self.tableWidget.item(r, v).text()) elif type(self.__mlist[r][v]) == float: if unicode(self.__mlist[r][v]) != ( self.tableWidget.item(r, v).text()): self.__mlist[r][v] = float( self.tableWidget.item(r, v).text()) elif type(self.__mlist[r][v]) == str: if unicode(self.__mlist[r][v] ) != self.tableWidget.item(r, v).text(): self.__mlist[r][v] = str( self.tableWidget.item(r, v).text()) elif type(self.__mlist[r][v]) == unicode: if (self.__mlist[r][v]) != self.tableWidget.item( r, v).text(): self.__mlist[r][v] = self.tableWidget.item( r, v).text() else: print type(self.__mlist[r][v]) # 执行数据校验函数 self.erlist = checkDataByDataType(self.__mlist, self.impType) if len(self.erlist) > 0: self.initListView(self.erlist) QMessageBox.information(self.parent, u'数据校验', u'数据校验失败,请检查数据正确性后,再导入到地图中') self.__isJy = False else: QMessageBox.information(self.parent, u'数据校验', u'数据校验成功,没有错误数据') self.__isJy = True else: QMessageBox.warning(self.parent, u'数据校验', u'请先导入Excel数据后再操作!') # 导入数据到地图中 def impdateClick(self): if self.__isJy: # 如果数据校验成功 if self.impType == ImpDateType.SITEANDCELL: # 导入基站小区 importDataToLayer = ImportDataToLayer(self.iface, self.__mlist, self.parent) if importDataToLayer.importSiteAndCellData(): QMessageBox.information(self.parent, u"导入数据", u"导入数据成功!") else: QMessageBox.critical(self.parent, u"导入数据", u"导入数据失败!") else: # 导入相邻小区 importDataToLayer = ImportDataToLayer(self.iface, self.__mlist, self.parent) if importDataToLayer.importSCellData(): QMessageBox.information(self.parent, u"导入数据", u"导入数据成功!") else: QMessageBox.critical(self.parent, u"导入数据", u"导入数据失败!") else: QMessageBox.warning(self.parent, u'数据导入', u'请确保校验数据成功后,再导入到地图中') # 编辑Action点击事件 def editClick(self): self.setEditTriggers(self.editAction.isChecked()) # 错误列表双击事件处理 def mlistClicked(self, listItem): itemData = listItem.data(Qt.UserRole) self.tableWidget.setFocus() self.tableWidget.setCurrentCell(itemData['row'], itemData['col']) # 选框改变事件 def comboxChange(self, index): self.updateType(index) # 字段验证是否为空 def __validNull(self, name, col, row, itm, rowitm): if itm is None or itm == '': tmpMap = {} tmpMap['col'] = col tmpMap['row'] = row tmpMap['msg'] = unicode(name) + u'不能为空' tmpMap['item'] = rowitm return tmpMap else: return None # 导入数据线程开始信号 绑定函数 def impStart(self): self.setStatusBarMsg(u'准备导入...') # 导入数据线程发生异常信号 绑定函数 def impError(self, e, exception_string): self.setStatusBarMsg(u'发生错误:' + unicode(e)) QMessageBox.warning(self.parent, u'Excel数据导入', u'发生错误:' + unicode(e)) # 导入数据线程完成信号 绑定函数 def impFinish(self, mylist): self.__mlist = [] self.__mlist.extend(mylist) self.mthread.quit() self.mthread.wait() self.mthread.deleteLater() self.impDateThread.deleteLater() self.tableWidget.clearContents() self.listWidget.clear() self.initTable(self.__mlist) self.setStatusBarMsg(u'数据导入完成...') self.__isJy = False # 导入完数据后,说明需要重新验证数据的正确性 # 导入数据到地图线程发生异常信号 绑定函数 def impError1(self, e, exception_string): self.setStatusBarMsg(u"导入数据发生错误") QMessageBox.critical(self, u'数据导入', u"发生错误:" + unicode(e)) # 导入数据到地图线程完成信号 绑定函数 def impFinish1(self, mylist): self.threadImp.quit() self.threadImp.wait() self.threadImp.deleteLater() self.impFeatureThread.deleteLater() remsg = u'数据导入完成!' layer = None if self.impType == LayerType.SITE: # remsg = u'基站' + remsg layer = getLayerByName(u'基站', self.iface) elif self.impType == LayerType.CELL: # remsg = u'小区' + remsg layer = getLayerByName(u'小区', self.iface) else: remsg = u'相邻小区' + remsg layer = getLayerByName(u'相邻小区', self.iface) self.setStatusBarMsg(remsg) layer.updateExtents() # 更新地图数据 self.iface.actionDraw().trigger() QMessageBox.information(self, u'数据导入', remsg) merlist = [] for eritm in self.erlist: merlist.append(eritm['item']) self.tableWidget.clearContents() # 先清楚表格的内容,再将错误的行显示到表格中 self.initTable(merlist)
class multirun_widget(QWidget): """Widget for editing multirun values. Keyword arguments: tr -- a translate instance that contains the experimental sequence nrows -- number of rows = number of multirun steps. ncols -- number of columns = number of channels to change in one step. order -- the order to produce the variables list in: ascending - with repeats next to each other descending - with repeats next to each other random - completely randomise the order coarse random - randomise order but repeats next to each other unsorted - make an ascending list, then repeat the list """ multirun_vals = pyqtSignal(np.ndarray) # the array of multirun values progress = pyqtSignal(str) # string detailing the progress of the multirun def __init__(self, tr, nrows=1, ncols=1, order='ascending'): super().__init__() self.tr = tr # translator for the current sequence self.mrtr = tr.copy() # translator for multirun sequence self.msglist = [] # list of multirun sequences as XML string self.ind = 0 # index for how far through the multirun we are self.nrows = nrows self.ncols = ncols self.types = OrderedDict([('measure', int), ('measure_prefix', str), ('1st hist ID', int), ('Variable label', str), ('Order', str), ('Type', strlist), ('Analogue type', strlist), ('Time step name', listlist), ('Analogue channel', listlist), ('runs included', listlist), ('Last time step run', str), ('Last time step end', str), ('# omitted', int), ('# in hist', int), ('list index', strlist)]) self.ui_param = OrderedDict([ ('measure', 0), ('measure_prefix', 'Measure0'), ('1st hist ID', -1), ('Variable label', ''), ('Order', order), ('Type', ['Time step length'] * ncols), ('Analogue type', ['Fast analogue'] * ncols), ('Time step name', [[]] * ncols), ('Analogue channel', [[]] * ncols), ('runs included', [[] for i in range(nrows)]), ('Last time step run', r'C:\Users\lab\Desktop\DExTer 1.4\Last Timesteps\feb2020_940and812.evt' ), ('Last time step end', r'C:\Users\lab\Desktop\DExTer 1.4\Last Timesteps\feb2020_940and812.evt' ), ('# omitted', 5), ('# in hist', 100), ('list index', ['0'] * ncols) ]) self.awg_args = [ 'duration_[ms]', 'off_time_[us]', 'freqs_input_[MHz]', 'start_freq_[MHz]', 'end_freq_[MHz]', 'hybridicity', 'num_of_traps', 'distance_[um]', 'tot_amp_[mV]', 'dc_offset_[mV]', 'start_amp', 'end_amp', 'start_output_[Hz]', 'end_output_[Hz]', 'freq_amp', 'mod_freq_[kHz]', 'mod_depth', 'freq_phase_[deg]', 'freq_adjust', 'amp_adjust', 'freqs_output_[Hz]', 'num_of_samples', 'duration_loop_[ms]', 'number_of_cycles' ] self.dds_args = [ 'Freq', 'Phase', 'Amp', 'Start_add', 'End_add', 'Step_rate', 'Sweep_start', 'Sweep_end', 'Pos_step', 'Neg_step', 'Pos_step_rate', 'Neg_step_rate' ] self.slm_args = [ 'f', 'period', 'angle', 'radius', 'gradient', 'shift', 'radial', 'azimuthal', 'amplitude' ] self.column_options = [ 'Analogue voltage', 'AWG1 chan : seg', 'AWG2 chan : seg', 'DDS1 port : profile', 'DDS2 module : profile', 'SLM holograms' ] # these analogue types require the analogue options self.col_range_text = [''] * ncols self.COM = ['RB1A', 'RB2', 'RB3', 'RB4', 'RB1B'] # DDS COM port connections self.COM2 = ['1557', '977', '1013', '420'] # DDS2 module connections self.mr_param = copy.deepcopy( self.ui_param) # parameters used for current multirun self.mr_vals = [] # multirun values for the current multirun self.mr_queue = [ ] # list of parameters, sequences, and values to queue up for future multiruns self.appending = False # whether the current multirun will be appended on to the displayed results self.multirun = False # whether a multirun is running or not self.QueueWindow = QMainWindow() # window for editing mr queue self.QueueWindow.setStyleSheet("background-color: cyan;") self.queue_ui = Ui_QueueWindow(self.mr_queue) self.queue_ui.setupUi(self.QueueWindow) self.init_UI() # make the widgets self.ss = sequenceSaver(self.mrtr, self.mr_vals, self.mr_param, '') # used to save sequences def make_label_edit(self, label_text, layout, position=[0, 0, 1, 1], default_text='', validator=None): """Make a QLabel with an accompanying QLineEdit and add them to the given layout with an input validator. The position argument should be [row number, column number, row width, column width].""" label = QLabel(label_text, self) layout.addWidget(label, *position) line_edit = QLineEdit(self) if np.size(position) == 4: position[1] += 1 layout.addWidget(line_edit, *position) line_edit.setText(default_text) line_edit.setValidator(validator) return label, line_edit def init_UI(self): """Create all of the widget objects required""" layout = QVBoxLayout() self.setLayout(layout) # place scroll bars if the contents of the window are too large scroll = QScrollArea(self) layout.addWidget(scroll) scroll_content = QWidget(scroll) scroll.setWidgetResizable(True) scroll.setFixedHeight(800) self.grid = QGridLayout() scroll_content.setLayout(self.grid) #### validators for user input #### double_validator = QDoubleValidator() # floats int_validator = QIntValidator(0, 10000000) # positive integers msr_validator = QIntValidator(-1, 1000000) # integers >= -1 nat_validator = QIntValidator(1, 10000000) # natural numbers col_validator = QIntValidator(1, self.ncols - 1) # for number of columns #### table dimensions and ordering #### # choose the number of rows = number of multirun steps labels = ['# Omit', '# in Histogram', '# Columns', '# Rows'] default = ['5', '100', str(self.ncols), str(self.nrows)] vldtr = [int_validator, nat_validator, nat_validator, nat_validator] self.omit_edit, self.nhist_edit, self.cols_edit, self.rows_edit = [ self.make_label_edit(labels[i], self.grid, [0, 2 * i, 1, 1], default[i], vldtr[i])[1] for i in range(4) ] self.cols_edit.textChanged[str].connect(self.change_array_size) self.rows_edit.textChanged[str].connect(self.change_array_size) self.omit_edit.editingFinished.connect(self.update_repeats) self.nhist_edit.editingFinished.connect(self.update_repeats) # choose the order self.order_edit = QComboBox(self) self.order_edit.addItems( ['ascending', 'descending', 'random', 'coarse random', 'unsorted']) self.grid.addWidget(self.order_edit, 0, 8, 1, 1) #### create multirun list of values #### # metadata for the multirun list: which channels and timesteps self.measures = OrderedDict() labels = ['Variable label', 'measure', 'measure_prefix', '1st hist ID'] defaults = ['Variable 0', '0', 'Measure0', '0'] for i in range(len(labels)): label = QLabel(labels[i], self) self.grid.addWidget(label, i + 1, 0, 1, 1) self.measures[labels[i]] = QLineEdit(defaults[i], self) self.measures[labels[i]].textChanged.connect(self.update_all_stats) self.grid.addWidget(self.measures[labels[i]], i + 1, 1, 1, 3) self.measures['measure'].setValidator(int_validator) self.measures['1st hist ID'].setValidator(msr_validator) label.setText('1st ID (-1 to append)') # change label self.chan_choices = OrderedDict() labels = [ 'Type', 'Time step name', 'Analogue type', 'Analogue channel' ] sht = self.tr.get_esc()[2][2:] # 'Sequence header top' options = [ [ 'Time step length', 'Analogue voltage', 'GPIB', 'AWG1 chan : seg', 'AWG2 chan : seg', 'DDS1 port : profile', 'DDS2 module : profile', 'SLM holograms', 'Other' ], list( map(str.__add__, [str(i) for i in range(len(sht))], [': ' + hc[6][1].text for hc in sht])), # time step names ['Fast analogue', 'Slow analogue'], self.get_anlg_chans('Fast') ] positions = [[1, 4, 3, 2], [1, 6, 6, 1], [1, 7, 3, 1], [1, 8, 6, 1]] widgets = [QComboBox, QListWidget] for i in range(0, len(labels)): self.chan_choices[labels[i]] = widgets[i % 2]() if i % 2: self.chan_choices[labels[i]].setSelectionMode(3) self.chan_choices[labels[i]].addItems(options[i]) self.grid.addWidget(self.chan_choices[labels[i]], *positions[i]) self.chan_choices['Type'].currentTextChanged[str].connect( self.change_mr_type) self.chan_choices['Analogue type'].currentTextChanged[str].connect( self.change_mr_anlg_type) self.chan_choices['Analogue channel'].setEnabled(False) # enter desired time step selection via python cmd self.index_slice = QLineEdit('range(0,1,2)', self) self.grid.addWidget(self.index_slice, 3, 4, 3, 2) self.apply_slice_btn = QPushButton('Apply range', self) self.grid.addWidget(self.apply_slice_btn, 4, 4, 3, 2) self.apply_slice_btn.clicked.connect(self.apply_slice) # AWG takes a list for some arguments, so needs an index label = QLabel('List index:', self) self.grid.addWidget(label, 3, 7, 3, 1) self.list_index = QLineEdit('0', self) self.grid.addWidget(self.list_index, 4, 7, 3, 1) self.list_index.setValidator(int_validator) self.list_index.textEdited[str].connect(self.save_chan_selection) # add a new list of multirun values to the array self.col_index = self.make_label_edit('column index:', self.grid, position=[5, 0, 1, 1], default_text='0', validator=col_validator)[1] self.col_range = QLineEdit('np.linspace(0,1,%s)' % (self.nrows), self) self.grid.addWidget(self.col_range, 5, 2, 1, 2) # show the previously selected channels for this column: self.chan_choices['Time step name'].itemClicked.connect( self.save_chan_selection) self.chan_choices['Analogue channel'].itemClicked.connect( self.save_chan_selection) self.col_range.editingFinished.connect(self.save_chan_selection) self.col_index.textChanged[str].connect(self.set_chan_listbox) # add the column to the multirun values array add_var_button = QPushButton('Add column', self) add_var_button.clicked.connect(self.add_column_to_array) add_var_button.resize(add_var_button.sizeHint()) self.grid.addWidget(add_var_button, 6, 0, 1, 1) # clear the current list of user variables clear_vars_button = QPushButton('Clear', self) clear_vars_button.clicked.connect(self.clear_array) clear_vars_button.resize(clear_vars_button.sizeHint()) self.grid.addWidget(clear_vars_button, 6, 1, 1, 1) # suggest new measure when multirun started self.suggest_button = QPushButton('Auto-increment measure', self, checkable=True, checked=True) self.suggest_button.resize(self.suggest_button.sizeHint()) self.grid.addWidget(self.suggest_button, 6, 2, 1, 2) # choose last time step for multirun lts_label = QLabel('Last time step: ', self) self.grid.addWidget(lts_label, 7, 0, 1, 1) self.last_step_run_edit = self.make_label_edit('Running: ', self.grid, position=[7, 1, 1, 3])[1] self.last_step_run_edit.setText(self.ui_param['Last time step run']) self.last_step_run_edit.textChanged[str].connect(self.update_last_step) self.last_step_end_edit = self.make_label_edit('End: ', self.grid, position=[7, 5, 1, 3])[1] self.last_step_end_edit.setText(self.ui_param['Last time step end']) self.last_step_end_edit.textChanged[str].connect(self.update_last_step) # display current progress multirun_progress = QLabel( 'User variable: , omit 0 of 0 files, 0 of 100 histogram files, 0% complete' ) self.grid.addWidget(multirun_progress, 8, 0, 1, 12) reset_slot(self.progress, multirun_progress.setText, True) # table stores multirun values: self.table = QTableWidget(self.nrows, self.ncols) self.reset_array() self.grid.addWidget(self.table, 9, 0, 20, 12) scroll.setWidget(scroll_content) #### #### array editing functions #### #### def reset_array(self, newvals=None): """Empty the table of its values. If newvals are supplied then it should have the right shape (rows, cols) so that it can be used to fill the table items.""" self.table.setHorizontalHeaderLabels(list(map(str, range(self.ncols)))) if not newvals: newvals = [[''] * self.ncols] * self.nrows for i in range(self.table.rowCount()): for j in range(self.ncols): self.table.setItem(i, j, QTableWidgetItem()) self.table.item(i, j).setText(newvals[i][j]) def clear_array(self): """Empty the table of its values and reset the selected channels.""" self.reset_array() self.ui_param['Type'] = ['Time step length'] * self.ncols self.ui_param['Analogue type'] = ['Fast analogue'] * self.ncols self.ui_param['Time step name'] = [[]] * self.ncols self.ui_param['Analogue channel'] = [[]] * self.ncols self.ui_param['list index'] = ['0'] * self.ncols self.col_range_text = self.col_range_text[:self.ncols] + [''] * ( self.ncols - len(self.col_range_text)) self.set_chan_listbox(0) def check_table(self): """Check that there are values in each of the cells of the array.""" try: for i in range(self.table.rowCount()): for j in range(self.table.columnCount()): _ = float(self.table.item(i, j).text()) return 1 except ValueError: return 0 def get_table(self): """Return a list of all the values in the multirun array table""" return [[ self.table.item(i, j).text() for j in range(self.table.columnCount()) ] for i in range(self.table.rowCount())] def change_array_size(self): """Update the size of the multirun array based on the number of rows and columns specified in the line edit.""" self.nrows = int(self.rows_edit.text()) if self.rows_edit.text() else 1 if self.nrows < 1: self.nrows = 1 self.table.setRowCount(self.nrows) self.ncols = int(self.cols_edit.text()) if self.cols_edit.text() else 1 if self.ncols < 1: self.ncols = 1 self.table.setColumnCount(self.ncols) self.col_index.setValidator(QIntValidator(1, self.ncols - 1)) if self.col_index.text() and int( self.col_index.text()) > self.ncols - 1: self.col_index.setText(str(self.ncols - 1)) self.reset_array() self.col_range_text = self.col_range_text[:self.ncols] + [''] * ( self.ncols - len(self.col_range_text)) self.ui_param['runs included'] = [[] for i in range(self.nrows)] for key, default in zip([ 'Type', 'Analogue type', 'Time step name', 'Analogue channel', 'list index' ], ['Time step length', 'Fast analogue', [], [], '0']): for i in range(len(self.ui_param[key]), self.ncols): self.ui_param[key].append(default) if len(self.ui_param[key]) > self.ncols: self.ui_param[key] = self.ui_param[key][:self.ncols] def update_all_stats(self, toggle=False): """Shorthand to update the values of the stats dictionary from the text labels.""" self.update_repeats() self.update_last_step() for key in self.measures.keys( ): # ['Variable label', 'measure', 'measure_prefix', '1st hist ID'] if self.measures[key].text( ): # don't do anything if the line edit is empty try: self.ui_param[key] = self.types[key]( self.measures[key].text()) except: pass # probably while user was typing the '-' in '-1' def update_repeats(self, txt=''): """Take the current values of the line edits and use them to set the number of omitted and number of included runs in a histogram.""" self.ui_param['# omitted'] = int( self.omit_edit.text()) if self.omit_edit.text() else 0 self.ui_param['# in hist'] = int( self.nhist_edit.text()) if self.nhist_edit.text() else 1 def update_last_step(self, txt=''): """Save the current values of the last time step file paths.""" self.ui_param['Last time step run'] = self.last_step_run_edit.text() self.ui_param['Last time step end'] = self.last_step_end_edit.text() def apply_slice(self): """Use the text in the index slice line edit to select time steps""" try: self.chan_choices['Time step name'].clearSelection() for i in eval(self.index_slice.text()): try: self.chan_choices['Time step name'].item(i).setSelected( True) except AttributeError: pass # index out of range self.save_chan_selection() except (TypeError, ValueError, NameError) as e: warning('Invalid selection command for multirun timesteps "' + self.index_slice.text() + '".\n' + str(e)) def add_column_to_array(self): """Make a list of values and add it to the given column in the multirun values array. The function is chosen by the user. Values are repeated a set number of times, ordered according to the ComboBox text. The selected channels are stored in lists.""" try: # make the list of values table = np.array(self.get_table()).T c = [column.astype(float) for column in table if '' not in column] vals = eval(self.col_range.text()) except Exception as e: warning('Add column to multirun: invalid syntax "' + self.col_range.text() + '".\n' + str(e)) return 0 col = int(self.col_index.text()) if self.col_index.text() else 0 # store the selected channels self.ui_param['Order'] = self.order_edit.currentText() for key in self.measures.keys( ): # ['Variable label', 'measure', 'measure_prefix', '1st hist ID'] if self.measures[key].text( ): # don't do anything if the line edit is empty self.ui_param[key] = self.types[key](self.measures[key].text()) # order the list of values if self.ui_param['Order'] == 'descending': vals = list(reversed(vals)) elif 'random' in self.ui_param['Order']: vals = list(vals) shuffle(vals) for i in range(self.table.rowCount()): try: # set vals in table cells self.table.item(i, col).setText('%.4f' % vals[i]) except IndexError: # occurs if invalid range self.table.item(i, col).setText('') #### multirun channel selection #### def reset_sequence(self, tr): """Update the translator object used to get the experimental sequence. This is used to set the labels for time step names and channel names. Note: the multirun sequence mrtr is not affected.""" self.tr = tr self.change_mr_type(self.chan_choices['Type'].currentText()) # note: selected channels might have changed order self.set_chan_listbox(self.col_index.text()) def save_chan_selection(self, arg=None): """When the user changes the selection of channels/timesteps for the given column, save it. The selection will be reloaded if the user changes the column and then comes back.""" try: if self.col_index.text(): col = int(self.col_index.text()) for key in ['Type', 'Analogue type']: self.ui_param[key][col] = self.chan_choices[ key].currentText() for key in ['Time step name', 'Analogue channel']: self.ui_param[key][col] = list( map(self.chan_choices[key].row, self.chan_choices[key].selectedItems())) self.ui_param['list index'][col] = int( self.list_index.text()) if self.list_index.text() else 0 self.col_range_text[col] = self.col_range.text() except (ValueError, IndexError) as e: error("Multirun couldn't save channel choices for column " + self.col_index.text() + '.\n' + str(e)) def set_chan_listbox(self, col): """Set the selected channels and timesteps with the values previously stored for the given column col. If there were no values stored previously or the index is out of range, reset the selection.""" try: col = int(col) if col else 0 mrtype = self.ui_param['Type'][col] antype = self.ui_param['Analogue type'][col] sel = { 'Time step name': self.ui_param['Time step name'][col], 'Analogue channel': self.ui_param['Analogue channel'][col] if any( mrtype == x for x in self.column_options) else [] } list_ind = self.ui_param['list index'][col] col_range_txt = self.col_range_text[col] except (IndexError, ValueError): mrtype, antype = 'Time step length', 'Fast analogue' sel = {'Time step name': [], 'Analogue channel': []} list_ind = 0 col_range_txt = '' self.col_range.setText(col_range_txt) self.list_index.setText(str(list_ind)) self.chan_choices['Type'].setCurrentText(mrtype) self.chan_choices['Analogue type'].setCurrentText(antype) self.chan_choices['Analogue channel'].setEnabled( any(mrtype == x for x in self.column_options)) for key in ['Time step name', 'Analogue channel']: self.chan_choices[key].setCurrentRow( 0, QItemSelectionModel.Clear) # clear previous selection try: for i in sel[key]: # select items at the stored indices self.chan_choices[key].item(i).setSelected(True) except IndexError: pass # perhaps sequence was updated but using old selection indices except AttributeError as e: warning( "Couldn't set channels for the loaded multirun parameters. Load the sequence first, then load multirun parameters.\n" + str(e)) def setListboxFlag(self, listbox, flag): """Set the items of the listbox all have the given flag. e.g. self.setListboxFlag(self.chan_choices['Time step name'], ~Qt.ItemIsEditable)""" for i in range(listbox.count()): item = listbox.item(i) item.setFlags(item.flags() | flag) def get_anlg_chans(self, speed): """Return a list of name labels for the analogue channels. speed -- 'Fast' or 'Slow'""" chans = self.tr.get_esc()[5 if speed == 'Fast' else 10][2:] return [c[2][1].text + ': ' + c[3][1].text for c in chans] def change_mr_type(self, newtype): """Enable/Disable list boxes to reflect the multirun type: newtype[str] -- Time step length: only needs timesteps -- Analogue voltage: also needs channels -- AWG: takes float values but with a list index.""" sht = self.tr.get_esc()[2][2:] # 'Sequence header top' if newtype == 'AWG1 chan : seg' or newtype == 'AWG2 chan : seg': self.chan_choices['Time step name'].clear() self.chan_choices['Time step name'].addItems( [str(i) + ', ' + str(j) for j in range(100) for i in range(2)]) reset_slot( self.chan_choices['Analogue type'].currentTextChanged[str], self.change_mr_anlg_type, False) self.chan_choices['Analogue type'].clear() self.chan_choices['Analogue type'].addItems(['AWG Parameter']) self.chan_choices['Analogue channel'].setEnabled(True) self.chan_choices['Analogue channel'].clear() self.chan_choices['Analogue channel'].addItems(self.awg_args) elif 'DDS' in newtype: self.chan_choices['Time step name'].clear() if 'DDS2' in newtype: ddsoptions = [ '%s : P%s - ' % (i + 1, j) + self.COM2[i] for i in range(4) for j in range(8) ] for i in range(4): ddsoptions.insert(i * 9 + 8, '%s : aux - ' % (i + 1) + self.COM2[i]) else: ddsoptions = [ 'COM%s : P%s - ' % (i + 7, j) + self.COM[i] for i in range(5) for j in range(8) ] for i in range(5): ddsoptions.insert(i * 9 + 8, 'COM%s : aux - ' % (i + 7) + self.COM[i]) self.chan_choices['Time step name'].addItems(ddsoptions) reset_slot( self.chan_choices['Analogue type'].currentTextChanged[str], self.change_mr_anlg_type, False) self.chan_choices['Analogue type'].clear() self.chan_choices['Analogue type'].addItems(['DDS Parameter']) self.chan_choices['Analogue channel'].setEnabled(True) self.chan_choices['Analogue channel'].clear() self.chan_choices['Analogue channel'].addItems(self.dds_args) elif newtype == 'SLM holograms': self.chan_choices['Time step name'].clear() slmoptions = ['Hologram %s' % (i) for i in range(9)] self.chan_choices['Time step name'].addItems(slmoptions) reset_slot( self.chan_choices['Analogue type'].currentTextChanged[str], self.change_mr_anlg_type, False) self.chan_choices['Analogue type'].clear() self.chan_choices['Analogue type'].addItems(['Hologram Parameter']) self.chan_choices['Analogue channel'].setEnabled(True) self.chan_choices['Analogue channel'].clear() self.chan_choices['Analogue channel'].addItems(self.slm_args) else: if any(self.chan_choices['Analogue type'].currentText() == x for x in ['AWG Parameter', 'DDS Parameter', 'Hologram Parameter']): self.chan_choices['Analogue type'].clear() self.chan_choices['Analogue type'].addItems( ['Fast analogue', 'Slow analogue']) self.chan_choices['Analogue type'].currentTextChanged[ str].connect(self.change_mr_anlg_type) if newtype == 'Other': self.chan_choices['Analogue channel'].setEnabled(False) self.chan_choices['Time step name'].clear() self.chan_choices['Time step name'].addItems(['Variable']) elif newtype == 'Time step length': self.chan_choices['Analogue channel'].setEnabled(False) self.chan_choices['Time step name'].clear() self.chan_choices['Time step name'].addItems( list( map(str.__add__, [str(i) for i in range(len(sht))], [': ' + hc[6][1].text for hc in sht]))) # time step names elif newtype == 'Analogue voltage': self.chan_choices['Time step name'].clear() self.chan_choices['Time step name'].addItems( list( map(str.__add__, [str(i) for i in range(len(sht))], [': ' + hc[6][1].text for hc in sht]))) # time step names self.chan_choices['Analogue channel'].setEnabled(True) self.chan_choices['Analogue channel'].clear() self.chan_choices['Analogue channel'].addItems( self.get_anlg_chans( self.chan_choices['Analogue type'].currentText().split( ' ')[0])) def change_mr_anlg_type(self, newtype): """Change the analogue channels listbox when fast/slow analogue channels are selected.""" if self.chan_choices['Analogue channel'].isEnabled(): self.chan_choices['Analogue channel'].clear() self.chan_choices['Analogue channel'].addItems( self.get_anlg_chans( self.chan_choices['Analogue type'].currentText().split( ' ')[0])) def get_next_index(self, rn): """Choose the next index from the rows of the table to use in the multirun, based on the order chosen. rn: the ID of the current run within the multirun. make rn modulo nrows so that there isn't an index error on the last run.""" # if self.mr_param['Order'] == 'unsorted': # return rn % self.nrows # elif self.mr_param['Order'] == 'random': # return randint(0, self.nrows - 1) # else: # if descending, ascending, or coarse random, the order has already been set return (rn // (self.mr_param['# omitted'] + self.mr_param['# in hist']) ) % len(self.mr_param['runs included'] ) # ID of histogram in repetition cycle def get_next_sequence(self, i=None): """Use the values in the multirun array to make the next sequence to run in the multirun. Uses saved mr_param not UI""" if i == None: i = self.ind # row index esc = self.mrtr.get_esc() # shorthand num_s = len(esc[2]) - 2 # number of steps try: for col in range(len(self.mr_vals[i])): # edit the sequence try: val = float(self.mr_vals[i][col]) if self.mr_param['Type'][col] == 'Time step length': for head in [2, 9]: for t in self.mr_param['Time step name'][col]: esc[head][t + 2][3][1].text = str(val) elif self.mr_param['Type'][col] == 'Analogue voltage': for t in self.mr_param['Time step name'][col]: for c in self.mr_param['Analogue channel'][col]: if 'Fast' in self.mr_param['Analogue type'][ col]: esc[6][t + c * num_s + 3][3][1].text = str(val) else: esc[11][t + c * num_s + 3][3][1].text = str(val) except ValueError as e: pass # non-float variable self.mrtr.set_routine_name('Multirun ' + self.mr_param['Variable label'] + \ ': ' + self.mr_vals[i][0] + ' (%s / %s)'%(i+1, len(self.mr_vals))) except IndexError as e: error('Multirun failed to edit sequence at ' + self.mr_param['Variable label'] + ' = ' + self.mr_vals[i][0] + '\n' + str(e)) return self.mrtr.write_to_str() def get_all_sequences(self, save_dir=''): """Use the multirun array vals to make all of the sequences that will be used in the multirun, then store these as a list of XML strings.""" self.msglist = [] for i in range(len(self.mr_vals)): self.msglist.append(self.get_next_sequence(i)) if not self.ss.isRunning(): self.ss = sequenceSaver(self.mrtr, self.mr_vals, self.mr_param, save_dir) self.ss.start(self.ss.LowestPriority) # save the sequences else: # a backup if the first is busy saving sequences self.s2 = sequenceSaver(self.mrtr, self.mr_vals, self.mr_param, save_dir) self.s2.start(self.s2.LowestPriority) #### save and load parameters #### def view_mr_queue(self): """Show the window for editing the multirun queue""" self.queue_ui.updateList() self.QueueWindow.show() def try_browse(self, title='Select a File', file_type='all (*)', open_func=QFileDialog.getOpenFileName): """Open a file dialog and retrieve a file name from the browser. title: String to display at the top of the file browser window file_type: types of files that can be selected open_func: the function to use to open the file browser""" try: if 'PyQt4' in sys.modules: file_name = open_func(self, title, '', file_type) elif 'PyQt5' in sys.modules: file_name, _ = open_func(self, title, '', file_type) return file_name except OSError: return '' # probably user cancelled def save_mr_params(self, save_file_name=''): """Save the variable label, measure, measure prefix, # runs omitted, # runs per histogram, multirun type, list of timesteps, multirun # analogue type, list of channels, and array of variables.""" if not save_file_name: save_file_name = self.try_browse( title='Save File', file_type='csv(*.csv);;all (*)', open_func=QFileDialog.getSaveFileName) if save_file_name: if hasattr(self.sender(), 'text') and self.sender().text() == 'Save Parameters': params, vals = self.ui_param, self.get_table() # save from UI else: params, vals = self.mr_param, self.mr_vals # save from multirun try: with open(save_file_name, 'w+') as f: f.write('Multirun list of variables:\n') f.write(';'.join([ ','.join( [vals[row][col] for col in range(len(vals[0]))]) for row in range(len(vals)) ]) + '\n') f.write(';'.join(params.keys()) + '\n') f.write(';'.join(map(str, list(params.values())))) except (PermissionError, FileNotFoundError) as e: error("Couldn't save Multirun params to file: %s\n" % save_file_name + str(e)) def load_mr_params(self, load_file_name=''): """Load the multirun variables array from a file.""" if not load_file_name: load_file_name = self.try_browse( title='Load File', file_type='csv(*.csv);;all (*)', open_func=QFileDialog.getOpenFileName) if load_file_name: with open(load_file_name, 'r') as f: _ = f.readline() vals = [ x.split(',') for x in f.readline().replace('\n', '').split(';') ] header = f.readline().replace('\n', '').split(';') params = f.readline().split(';') for i in range(len(header)): if header[i] in self.ui_param: try: self.ui_param[header[i]] = self.types[header[i]]( params[i]) except ValueError as e: error( 'Multirun editor could not load parameter: %s\n' % params[i] + str(e)) # store values in case they're overwritten after setText() nrows, ncols = np.shape(vals) # update array of values col = int(self.col_index.text()) if self.col_index.text() else 0 nhist, nomit = map( str, [self.ui_param['# in hist'], self.ui_param['# omitted']]) runstep, endstep = self.ui_param[ 'Last time step run'], self.ui_param['Last time step end'] # then update the label edits for key in self.measures.keys( ): # update variable label and measure reset_slot(self.measures[key].textChanged, self.update_all_stats, False) self.measures[key].setText(str(self.ui_param[key])) reset_slot(self.measures[key].textChanged, self.update_all_stats, True) self.set_chan_listbox(col if col < ncols else 0) self.rows_edit.setText(str(nrows)) # triggers change_array_size self.cols_edit.setText(str(ncols)) self.change_array_size() # don't wait for it to be triggered self.reset_array(vals) self.nhist_edit.setText(nhist) self.omit_edit.setText(nomit) self.last_step_run_edit.setText( runstep) # triggers update_last_step self.last_step_end_edit.setText(endstep) for i in range( len(header) ): # restore values as change_array_size loads defaults if header[i] in self.ui_param: try: self.ui_param[header[i]] = self.types[header[i]]( params[i]) except ValueError as e: pass def check_mr_params(self, save_results_path='.'): """Check that the multirun parameters are valid before adding it to the queue""" if 'PyDex default empty sequence' in self.tr.get_routine_name(): QMessageBox.warning( self, 'No sequence loaded', 'You must load a sequence before starting a multirun.') return 0 results_path = os.path.join(save_results_path, self.ui_param['measure_prefix']) self.appending = False # first check if the measure folder already exists with some files in imax = -1 try: filelist = os.listdir(results_path) for fname in filelist: if 'params' in fname: try: # look for multirun parameters file with open(os.path.join(results_path, fname), 'r') as f: _ = f.readline() vals = f.readline().replace('\n', '').split(';') header = f.readline().replace('\n', '').split(';') params = f.readline().split(';') imax = max( imax, len(vals) + int(params[header.index('1st hist ID')]) - 1) except: pass except (FileNotFoundError, PermissionError): pass # then check the multirun queue for m in self.mr_queue: if self.ui_param['measure_prefix'] == m[0]['measure_prefix']: imax = max(imax, len(m[2]) + m[0]['1st hist ID'] - 1) if self.ui_param['1st hist ID'] == -1: # append at the end self.appending = True self.ui_param['1st hist ID'] = imax + 1 if imax >= 0 else 0 if (os.path.isdir(results_path) or self.ui_param['measure_prefix'] in [ x[0]['measure_prefix'] for x in self.mr_queue ]) and imax >= self.ui_param['1st hist ID']: # this measure exists, check if user wants to overwrite reply = QMessageBox.question( self, 'Confirm Overwrite', "Results path already exists, do you want to overwrite the csv and dat files?\n" + results_path, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: if self.appending: # if appending, reset ui_param to -1. Also happens at end of multirun in runid.py self.measures['1st hist ID'].setText('') self.measures['1st hist ID'].setText('-1') return 0 # elif reply == QMessageBox.Yes: # try: # for fn in os.listdir(results_path): # if '.csv' in fn or '.dat' in fn: # os.remove(os.path.join(results_path, fn)) # except Exception as e: # warning('Multirun could not remove files from '+results_dir+'\n'+str(e)) # parameters are valid, add to queue self.mr_queue.append([ copy.deepcopy(self.ui_param), self.tr.copy(), self.get_table(), self.appending ]) if self.appending: # if appending, reset ui_param to -1. Also happens at end of multirun in runid.py self.measures['1st hist ID'].setText('') self.measures['1st hist ID'].setText('-1') if self.suggest_button.isChecked( ): # suggest new multirun measure ID and prefix n = self.ui_param['measure'] + 1 self.measures['measure'].setText(str(n)) self.measures['measure_prefix'].setText('Measure' + str(n)) return 1
class RemoveSentencesDlg(QDialog): def __init__(self): super(RemoveSentencesDlg, self).__init__() self.removeList = {} self.initUI() def initUI(self): ## create a font type for the label fontLabel = QFont('SansSerif', 14) ## create a label self.label = QLabel(self) self.label.setAutoFillBackground(True) self.label.setAlignment(Qt.AlignCenter) self.label.setGeometry(QRect(200, 10, 400, 40)) self.label.setFont(fontLabel) ## set the text for the Label self.label.setText('Remove the Sentences') ## Create a Table to hold all the sentences self.sentenceTable = QTableWidget(self) ## set the size and the position of the table self.sentenceTable.setGeometry(QRect(10, 60, 800, 400)) ## set the column count for the table self.sentenceTable.setColumnCount(1) sentenceHeaderList = ['Sentences From Table'] self.sentenceTable.setHorizontalHeaderLabels(sentenceHeaderList) self.sentenceTable.resizeColumnsToContents() self.sentenceTable.horizontalHeader().setStretchLastSection(True) self.sentenceTable.verticalHeader().setStretchLastSection(True) # Create a Remove button self.removeButton = QPushButton('Remove', self) self.removeButton.move(350, 600) # Create a close button self.closeButton = QPushButton('Close', self) self.closeButton.move(450, 600) ## Create signal for the remove button self.connect(self.removeButton, SIGNAL("clicked()"), self.onRemoveClicked) ## Create signal for the close button self.connect(self.closeButton, SIGNAL("clicked()"), self.closeClicked) ## Create signal for the sentence table self.connect(self.sentenceTable, SIGNAL('cellClicked(int, int)'), self.sentenceStateChanged) ## Get sentences from the database table self.getSentencesFromDatabase() self.setGeometry(800, 800, 900, 650) def getSentencesFromDatabase(self): ## returns the sentence and the corresponding word associated with it self.twoTypeList = data.Data().getSentencesFromDatabase() if len(self.twoTypeList) == 2: self.sentenceList = self.twoTypeList[0] ## load the sentences in the Table Widget self.loadSentencesInTable() def loadSentencesInTable(self): self.col = 0 if len(self.sentenceList) > 0: self.sentenceTable.setRowCount(len(self.sentenceList)) cellList = [] ## Create QTableWidgetItems from the sentence list for sentence in self.sentenceList: item = QTableWidgetItem(QString(sentence)) item.setFlags(Qt.ItemFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)) item.setCheckState(Qt.Unchecked) cellList.append(item) cellList.reverse() # set the widget items in the table for item in range(0, len(self.sentenceList)): self.sentenceTable.setItem(item, self.col, cellList.pop()) for index in range(0, len(self.sentenceList)): self.sentenceTable.verticalHeader().resizeSection(index, 100) if len(self.sentenceList) == 5: self.sentenceTable.setFixedHeight(500) if len(self.sentenceList) == 4: self.sentenceTable.setFixedHeight(400) elif len(self.sentenceList) == 3: self.sentenceTable.setFixedHeight(300) elif len(self.sentenceList) == 2: self.sentenceTable.setFixedHeight(200) elif len(self.sentenceList) == 1: self.sentenceTable.setFixedHeight(100) else: self.sentenceTable.clearContents() def sentenceStateChanged(self, row, col): if (self.sentenceTable.item(row, col).checkState() == 2): self.removeList[row] = self.sentenceTable.item(row, col).text() self.sentenceTable.item(row, col).setFlags(Qt.ItemFlags(Qt.ItemIsEditable | Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)) else: self.sentenceTable.item(row,col).setFlags(Qt.ItemFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)) del self.removeList[row] def onRemoveClicked(self): if len(self.removeList) == 0: QMessageBox.information(self, 'Remove Sentences', 'Select the Sentences to Delete') else: reply = QMessageBox.question(self, 'Remove Sentences', 'You want to delete the selected sentences', QMessageBox.Yes | QMessageBox.No) if reply == QMessageBox.Yes: for sentence in self.removeList: if sentence in self.sentenceList: self.sentenceList.remove(sentence) ## clear the contents of the Table self.sentenceTable.clearContents() cellList = [] ## Add the new entries into the table for sentence in self.sentenceList: item = QTableWidgetItem(QString(sentence)) item.setFlags(Qt.ItemFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)) item.setCheckState(Qt.Unchecked) cellList.append(item) cellList.reverse() for index in range(0, len(self.sentenceList)): self.sentenceTable.setItem(index, self.col, cellList.pop()) self.sentenceTable.setRowCount(len(self.sentenceList)) deleteSentences = [] for sentence in self.removeList.values(): deleteSentences.append(sentence) rowsDeletec = data.Data().deleteSentencesFromDatabase(deleteSentences) self.getSentencesFromDatabase() self.removeList = {} def closeClicked(self): reply = QMessageBox.question(self, "Remove Sentences", "Do you want to close the application", QMessageBox.Yes | QMessageBox.No) if reply == QMessageBox.Yes: self.reject()
class K800IRec(QWidget, mfso): def __init__(self): mfso.__init__(self, "K800i-Recover") self.name = "K800i-Recover" self.icon = None self.__disown__() def start(self, args): self.vfs = vfs.vfs() self.dumpnumber = 1 try : self.nor = args['nor'].value() self.nand = args['nand'].value() except IndexError: return try: self.spareSize = args["spare-size"].value() except IndexError: self.spareSize = 16 try: self.pageSize = args["page-size"].value() except IndexError: self.pageSize = 512 self.k800n = Node("k800-base") self.k800n.__disown__() self.boot = SEBootBlock(self.nor, self.pageSize) self.blockSize = self.boot.blockSize self.nandClean = SpareNode(self, self.nand, "nandfs", self.pageSize, self.spareSize, self.k800n) self.norFs = NorFs(self, self.k800n, self.nor, "norfs", self.boot) self.fullFs = FullFs(self, self.k800n, self.norFs, self.nandClean, "fullfs", self.boot) self.gdfs = GDFS(self, self.k800n, self.nor, "gdfs", self.boot) self.firmware = Firmware(self, self.k800n, self.nor, "firmware", self.boot.norfsoffset) self.tables = Tables(self.fullFs, self.blockSize) self.registerTree(self.nand, self.k800n) def createDump(self): text, ok = QInputDialog.getText(self, "Create dump", "dump name:", QLineEdit.Normal, "k800-restore-" + str(self.dumpnumber)) if ok and text != "": if (self.vfs.getnode(self.nand.absolute() + "/" + str(text)) == None): self.dumpnumber += 1 newroot = Node(str(text)) newroot.__disown__() for id in range(0, len(self.tables.tablesIdWriteMap) - 1): write = int(str(self.gtable.cellWidget(id, 0).currentText()), 16) self.tables.map[id] = self.tables.tablesIdWriteMap[id][write] virtual = VirtualMap(self, newroot, self.fullFs, self.tables, "virtual", self.blockSize) separt = SEPartitionBlock(virtual, self.boot.partitionblock, self.blockSize) self.createPart(separt, newroot, virtual) self.registerTree(self.nand, newroot) else : box = QMessageBox(QMessageBox.Warning, "Error", "Error node already exists", QMessageBox.NoButton, self) box.exec_() self.createDump() def createPart(self, separt, newroot, virtual): for part in separt.partTable: if part.start > 0: p = Partition(self, newroot, virtual, part, self.blockSize) def g_display(self): QWidget.__init__(self, None) self.layout = QVBoxLayout(self) self.hlayout = QSplitter(self) self.layout.insertWidget(0, self.hlayout) self.layout.setStretchFactor(self.hlayout, 1) self.gTable() self.viewTable() self.button = QPushButton("&Create dump") self.connect(self.button, SIGNAL("clicked()"), self.createDump) self.layout.addWidget(self.button) def viewTable(self): self.vtable = QTableWidget() self.vtable.setColumnCount(20) self.vtable.setRowCount(48) self.hlayout.addWidget(self.vtable) def viewTableUpdate(self, id): write = int(str(self.gtable.cellWidget(id, 0).currentText()), 16) t = self.tables.tablesIdWriteMap[id][write] l = t.blockList for x in xrange(0, len(t.blockList[0])): block = t.blockList[0][x] c = ((x) % 20) r = ((x) / 20) item = QTableWidgetItem(QString(hex(block))) tipBlock = (id * 960) + x item.setToolTip(QString(hex(tipBlock))) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.vtable.setItem(r ,c, item) def gTable(self): self.gtable = QTableWidget() self.gtable.setColumnCount(1) self.gtable.setRowCount(len(self.tables.tablesIdWriteMap)) self.gtable.setHorizontalHeaderItem(0, QTableWidgetItem(QString("version"))) self.hlayout.addWidget(self.gtable) self.sigMapper = QSignalMapper(self) for id in self.tables.tablesIdWriteMap: wlist = self.tables.tablesIdWriteMap[id] cbox = QComboBox(self.gtable) self.connect(cbox, SIGNAL("activated(QString)"), self.sigMapper, SLOT("map()")) self.sigMapper.setMapping(cbox, id) l = [] for write in wlist: l.append(write) l.sort() l.reverse() for write in l: cbox.addItem(QString(hex(write))) self.gtable.setCellWidget(id, 0, cbox) self.gtable.setVerticalHeaderItem(id, QTableWidgetItem(QString(hex(id)))) self.connect(self.sigMapper, SIGNAL("mapped(int)"), self.viewTableUpdate) self.gtable.setMaximumWidth(self.gtable.columnWidth(0) + self.gtable.verticalHeader().sectionSize(0) + 30) def updateWidget(self): pass
class K800IRec(QWidget, mfso): def __init__(self): mfso.__init__(self, "K800i-Recover") self.name = "K800i-Recover" self.icon = None self.__disown__() def start(self, args): self.vfs = vfs.vfs() self.dumpnumber = 1 try: self.nor = args['nor'].value() self.nand = args['nand'].value() except IndexError: return try: self.spareSize = args["spare-size"].value() except IndexError: self.spareSize = 16 try: self.pageSize = args["page-size"].value() except IndexError: self.pageSize = 512 self.k800n = Node("k800-base") self.k800n.__disown__() self.boot = SEBootBlock(self.nor, self.pageSize) self.blockSize = self.boot.blockSize self.nandClean = SpareNode(self, self.nand, "nandfs", self.pageSize, self.spareSize, self.k800n) self.norFs = NorFs(self, self.k800n, self.nor, "norfs", self.boot) self.fullFs = FullFs(self, self.k800n, self.norFs, self.nandClean, "fullfs", self.boot) self.gdfs = GDFS(self, self.k800n, self.nor, "gdfs", self.boot) self.firmware = Firmware(self, self.k800n, self.nor, "firmware", self.boot.norfsoffset) self.tables = Tables(self.fullFs, self.blockSize) self.registerTree(self.nand, self.k800n) def createDump(self): text, ok = QInputDialog.getText(self, "Create dump", "dump name:", QLineEdit.Normal, "k800-restore-" + str(self.dumpnumber)) if ok and text != "": if (self.vfs.getnode(self.nand.absolute() + "/" + str(text)) == None): self.dumpnumber += 1 newroot = Node(str(text)) newroot.__disown__() for id in range(0, len(self.tables.tablesIdWriteMap) - 1): write = int( str(self.gtable.cellWidget(id, 0).currentText()), 16) self.tables.map[id] = self.tables.tablesIdWriteMap[id][ write] virtual = VirtualMap(self, newroot, self.fullFs, self.tables, "virtual", self.blockSize) separt = SEPartitionBlock(virtual, self.boot.partitionblock, self.blockSize) self.createPart(separt, newroot, virtual) self.registerTree(self.nand, newroot) else: box = QMessageBox(QMessageBox.Warning, "Error", "Error node already exists", QMessageBox.NoButton, self) box.exec_() self.createDump() def createPart(self, separt, newroot, virtual): for part in separt.partTable: if part.start > 0: p = Partition(self, newroot, virtual, part, self.blockSize) def g_display(self): QWidget.__init__(self, None) self.layout = QVBoxLayout(self) self.hlayout = QSplitter(self) self.layout.insertWidget(0, self.hlayout) self.layout.setStretchFactor(self.hlayout, 1) self.gTable() self.viewTable() self.button = QPushButton("&Create dump") self.connect(self.button, SIGNAL("clicked()"), self.createDump) self.layout.addWidget(self.button) def viewTable(self): self.vtable = QTableWidget() self.vtable.setColumnCount(20) self.vtable.setRowCount(48) self.hlayout.addWidget(self.vtable) def viewTableUpdate(self, id): write = int(str(self.gtable.cellWidget(id, 0).currentText()), 16) t = self.tables.tablesIdWriteMap[id][write] l = t.blockList for x in xrange(0, len(t.blockList[0])): block = t.blockList[0][x] c = ((x) % 20) r = ((x) / 20) item = QTableWidgetItem(QString(hex(block))) tipBlock = (id * 960) + x item.setToolTip(QString(hex(tipBlock))) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.vtable.setItem(r, c, item) def gTable(self): self.gtable = QTableWidget() self.gtable.setColumnCount(1) self.gtable.setRowCount(len(self.tables.tablesIdWriteMap)) self.gtable.setHorizontalHeaderItem( 0, QTableWidgetItem(QString("version"))) self.hlayout.addWidget(self.gtable) self.sigMapper = QSignalMapper(self) for id in self.tables.tablesIdWriteMap: wlist = self.tables.tablesIdWriteMap[id] cbox = QComboBox(self.gtable) self.connect(cbox, SIGNAL("activated(QString)"), self.sigMapper, SLOT("map()")) self.sigMapper.setMapping(cbox, id) l = [] for write in wlist: l.append(write) l.sort() l.reverse() for write in l: cbox.addItem(QString(hex(write))) self.gtable.setCellWidget(id, 0, cbox) self.gtable.setVerticalHeaderItem( id, QTableWidgetItem(QString(hex(id)))) self.connect(self.sigMapper, SIGNAL("mapped(int)"), self.viewTableUpdate) self.gtable.setMaximumWidth( self.gtable.columnWidth(0) + self.gtable.verticalHeader().sectionSize(0) + 30) def updateWidget(self): pass