Beispiel #1
0
 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_()
Beispiel #2
0
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_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)
Beispiel #4
0
    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()
Beispiel #5
0
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()
Beispiel #6
0
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()
Beispiel #7
0
class CorrectorViewer(QtGui.QWidget):
    """
    List all corrector and select part to lower table
    """
    def __init__(self, cors, field, parent=None, nmax=4):
        super(CorrectorViewer, self).__init__(parent)
        self._nmax  = nmax
        self._field = field
        self._cors  = cors
        self._corlst1 = QtGui.QTreeWidget()
        self._header = dict([("Element", 0), ("Family", 1), ("s [m]", 2),
                             ("Alpha X", 3), ("Alpha Y", 4), ("Beta X", 5),
                             ("Beta Y", 6), ("Phi X", 7), ("Phi Y", 8),
                             ("Eta X", 9)])
        self._twiss = np.zeros((len(self._cors), 8), 'd')
        self._tunes = getTunes(source="database")
        self._corlst1.setColumnCount(len(self._header))
        self._corlst1.setHeaderLabels(
            sorted(self._header, key=self._header.get))
        self._corlst1.header().setStretchLastSection(False)
        prevcell = None
        for i,c in enumerate(self._cors):
            if c.cell and (prevcell is None or c.cell != prevcell.text(0)):
                # a new parent
                prevcell = QtGui.QTreeWidgetItem()
                prevcell.setText(0, c.cell)
                self._corlst1.addTopLevelItem(prevcell)
            it = QtGui.QTreeWidgetItem()
            it.setData(0, Qt.UserRole, i)
            it.setText(self._header["Element"], c.name)
            it.setText(self._header["Family"], c.family)
            it.setText(self._header["s [m]"], "%.3f" % c.sb)
            try:
                tw = getTwiss(c.name,
                              ["s", "alphax", "alphay", "betax", "betay",
                               "phix", "phiy", "etax"])
                self._twiss[i,:] = tw[0,:]
                it.setText(self._header["Alpha X"], "%.4f" % self._twiss[i,1])
                it.setText(self._header["Alpha Y"], "%.4f" % self._twiss[i,2])
                it.setText(self._header["Beta X"],  "%.4f" % self._twiss[i,3])
                it.setText(self._header["Beta Y"],  "%.4f" % self._twiss[i,4])
                it.setText(self._header["Phi X"],   "%.4f" % self._twiss[i,5])
                it.setText(self._header["Phi Y"],   "%.4f" % self._twiss[i,6])
                it.setText(self._header["Eta X"],   "%.4f" % self._twiss[i,7])
            except:
                it.setDisabled(True)
                pass

            if c.cell:
                prevcell.addChild(it)
            else:
                self._corlst1.addTopLevelItem(it)
                prevcell = it
            for j in range(2, len(self._header)):
                it.setTextAlignment(j, Qt.AlignRight)
        self._corlst1.expandAll()
        for i in range(len(self._header)):
            self._corlst1.resizeColumnToContents(i)
        #self._corlst1.setColumnWidth(0, 150)

        #self.elemlst.setSelectionMode(QAbstractItemView.MultiSelection)
        columns = ['Corrector', 's', 'Alpha', 'Beta',
                   'Phi', "dPhi", "Initial Bump", "Cur. Sp", "dBump",
                   "Final Rb"]
        self.table4 = QTableWidget(0, len(columns))
        #self.table4.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        hdview = QHeaderView(Qt.Horizontal)
        self.table4.setHorizontalHeaderLabels(columns)
        #for i in range(4):
        #    for j in range(len(columns)):
        #        it = QTableWidgetItem()
        #        if j > 0: it.setTextAlignment(
        #            Qt.AlignRight | Qt.AlignVCenter)
        #        if columns[j] != "dKick":
        #            it.setFlags(it.flags() & (~Qt.ItemIsEditable))
        #        self.table4.setItem(i, j, it)
        #self.table4.resizeColumnsToContents()
        #self.table4.horizontalHeader().setStretchLastSection(True)
        #hrow = self.table4.rowHeight(0)
        #htbl = (hrow * 4) + self.table4.horizontalHeader().height() +\
        #    2*self.table4.frameWidth()
        #self.table4.setMinimumHeight(htbl + 10)
        #self.table4.setMaximumHeight(htbl + 15)
        #self.table4.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        #print "Size:", htbl + 10
        self.table4.resize(self.table4.width(), 150)

        splitter = QtGui.QSplitter(Qt.Vertical)
        splitter.addWidget(self._corlst1)
        splitter.addWidget(self.table4)
        vbox1 = QtGui.QVBoxLayout()
        vbox1.addWidget(splitter)
        self.setLayout(vbox1)

        self.connect(self._corlst1, SIGNAL("doubleClicked(QModelIndex)"),
                     self.addCorrector)
        #self.connect(self.src, SIGNAL("returnPressed()"),
        #             self._calc_source)
        #self.connect(self.table4, SIGNAL("cellChanged(int, int)"),
        #             self.updateTable)

        #self.connect(self.table4, SIGNAL("doubleClicked(QModelIndex)"),
        #             self.delCorrector)
        self._x0 = fget(self._cors, "x", handle="setpoint", unitsys=None)
        self._y0 = fget(self._cors, "y", handle="setpoint", unitsys=None)


    def addCorrector(self, idx):
        if not self._corlst1.selectedItems(): return
        #print self._corlst1.itemFromIndex(idx).text(0)
        nrow = self.table4.rowCount()
        if nrow >= self._nmax:
            QtGui.QMessageBox.critical(
                self, "Local Orbit Bump",
                "ERROR: We need only {0} correctors.".format(self._nmax),
                QtGui.QMessageBox.Ok)
                #self.progress.setValue(0)
            return
        self.table4.setRowCount(nrow+1)
        it0 = self._corlst1.selectedItems()[-1]
        icor, ok = it0.data(0, Qt.UserRole).toInt()
        if icor < 0: return
        newc = self._cors[icor]
        for j in range(self.table4.columnCount()):
            it = QTableWidgetItem()
            if j > 0: it.setTextAlignment(
                Qt.AlignRight | Qt.AlignVCenter)
            header = self.table4.horizontalHeaderItem(j)
            if header.text() != "dBump":
                it.setFlags(it.flags() & (~Qt.ItemIsEditable))
            else:
                it.setData(Qt.DisplayRole, "0")
                it.setData(Qt.UserRole, 0.0)
            self.table4.setItem(nrow, j, it)
        self.table4.item(nrow,0).setData(Qt.UserRole, icor)
        for j,h in [(0, "Element"), (1, "s [m]")]:
            self.table4.item(nrow,j).setData(Qt.DisplayRole,
                                          it0.text(self._header[h]))
        for j in range(self._corlst1.columnCount()):
            it0.setForeground(j, Qt.red)
        it0.setDisabled(True)
        self.emit(SIGNAL("correctorAdded(PyQt_PyObject)"), newc)
        # use initial values

        self.updateTwiss()
        self.updateCorReadings()
        self.table4.resizeColumnsToContents()
        if self.table4.rowCount() == self._nmax:
            #print "All correctors are ready"
            self.emit(SIGNAL("correctorsComplete()"))

    def updateTwiss(self):
        if self._field == "x":
            jl = [self._header[h] for h in ["Alpha X", "Beta X", "Phi X"]]
            nu = self._tunes[0]
        elif self._field == "y":
            jl = [self._header[h] for h in ["Alpha Y", "Beta Y", "Phi Y"]]
            nu = self._tunes[1]
        else:
            raise RuntimeError("unknown cor field {0}".format(self._field))
        #print "index:", jl
        # if rows provided use it, otherwise use all
        for i in range(self.table4.rowCount()):
            elemname = self.table4.item(i,0).data(Qt.DisplayRole).toString()
            it0 = self._corlst1.findItems(
                elemname, Qt.MatchExactly | Qt.MatchRecursive)[0]

            self.table4.item(i,2).setText(it0.text(jl[0]))
            self.table4.item(i,3).setText(it0.text(jl[1]))
            self.table4.item(i,4).setText(it0.text(jl[2]))
            self.table4.item(i,4).setData(Qt.UserRole, float(it0.text(jl[2])))

            if i == 0:
                self.table4.item(i,5).setText("0.0")
                self.table4.item(i,5).setData(Qt.UserRole, 0.0)
            else:
                dph, ok = self.table4.item(i-1,5).data(Qt.UserRole).toFloat()
                ph0, ok = self.table4.item(i-1,4).data(Qt.UserRole).toFloat()
                ph1, ok = self.table4.item(i,4).data(Qt.UserRole).toFloat()
                dph = dph + ph1 - ph0
                if ph1 < ph0:
                    dph = dph + 2.0*np.pi*nu
                #print "Updating twiss:", i, dph
                self.table4.item(i,5).setData(Qt.UserRole, dph)
                self.table4.item(i,5).setText("%.5g" % dph)
            icor, ok = self.table4.item(i,0).data(Qt.UserRole).toInt()
            #c = self._cors[icor]
            #kick = self._cors[icor].get(self._field, unitsys=None)
            #self.table4.item(i,6).setData(Qt.UserRole, kick)
            #self.table4.item(i,6).setText("%.5g" % kick)
        #self.updateKickReadings(col=0)

    def clear(self):
        for i in range(self.table4.rowCount()):
            elemname = self.table4.item(i,0).data(Qt.DisplayRole).toString()
            it0 = self._corlst1.findItems(
                elemname, Qt.MatchExactly | Qt.MatchRecursive)[0]
            it0.setDisabled(False)
            for j in range(self._corlst1.columnCount()):
                it0.setForeground(j, Qt.black)
        self.table4.setRowCount(0)

    def updateCorReadings(self):
        for i in range(self.table4.rowCount()):
            icor, ok = self.table4.item(i,0).data(Qt.UserRole).toInt()
            cor = self._cors[icor]
            if self._field == "x":
                self.table4.item(i,6).setData(Qt.UserRole, self._x0[icor])
                self.table4.item(i,6).setText("%.5g" % self._x0[icor])
            elif self._field == "y":
                self.table4.item(i,6).setData(Qt.UserRole, self._y0[icor])
                self.table4.item(i,6).setText("%.5g" % self._y0[icor])
            kicksp = cor.get(self._field, handle="setpoint", unitsys=None)
            self.table4.item(i,7).setData(Qt.UserRole, float(kicksp))
            self.table4.item(i,7).setText("%.5g" % kicksp)
            kickrb = cor.get(self._field, handle="readback", unitsys=None)
            self.table4.item(i,9).setData(Qt.UserRole, float(kickrb))
            self.table4.item(i,9).setText("%.5g" % kickrb)


    def updateDbump(self, dkick):
        nrow = min(self.table4.rowCount(), len(dkick))
        for i in range(nrow):
            # dbump column is 8
            it = self.table4.item(i, 8)
            if dkick[i] is None:
                it.setData(Qt.DisplayRole, "")
                it.setData(Qt.UserRole, 0.0)
            else:
                it.setData(Qt.UserRole, float(dkick[i]))
                it.setData(Qt.DisplayRole, "{0}".format(dkick[i]))
        self.updateCorReadings()
        self.table4.resizeColumnsToContents()
        #print "(0,7)", self.table4.item(0, 7).data(Qt.UserRole).toFloat()
        #print "(0,7)", self.table4.item(0, 7).data(Qt.DisplayRole).toFloat()

    def applyKick(self):
        nrow = self.table4.rowCount()
        for i in range(nrow):
            icor, ok = self.table4.item(i,0).data(Qt.UserRole).toInt()
            cor = self._cors[icor]
            # Current SP: 7, dBump 8
            k0, ok = self.table4.item(i, 7).data(Qt.UserRole).toFloat()
            dk, ok = self.table4.item(i, 8).data(Qt.UserRole).toFloat()
            #print "Setting {0} {1}+{2} [A]".format(cor.name, k0, dk)
            cor.put(self._field, k0+dk, unitsys=None)

        # update the final readings
        self.updateCorReadings()

    def getTwiss(self):
        tw = {"s": [], "Alpha": [], "Beta": [],
              "Phi": [], "dPhi": []}
        nrow = self.table4.rowCount()
        for j in range(self.table4.columnCount()):
            header = self.table4.horizontalHeaderItem(j)
            if header.text() not in tw.keys():
                continue
            k = str(header.text())
            for i in range(nrow):
                it = self.table4.item(i, j)
                v0, ok0 = it.data(Qt.UserRole).toFloat()
                v1, ok1 = it.data(Qt.DisplayRole).toFloat()
                if ok0:
                    tw[k].append(v0)
                elif ok1:
                    tw[k].append(v1)
                else:
                    tw[k].append(np.nan)
        return tw

    def selectedCorrectors(self):
        ret = []
        for i in range(self.table4.rowCount()):
            icor, ok = self.table4.item(i,0).data(Qt.UserRole).toInt()
            ret.append(self._cors[icor])
        return ret

    def resetCorrectors(self):
        for i in range(self.table4.rowCount()):
            icor, ok = self.table4.item(i,0).data(Qt.UserRole).toInt()
            cor = self._cors[icor]
            if self._field == "x":
                kick = self._x0[icor]
            elif self._field == "y":
                kick = self._y0[icor]
            cor.put(self._field, kick, unitsys=None)
Beispiel #8
0
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 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()
        
Beispiel #10
0
class CorrectorViewer(QtGui.QWidget):
    """
    List all corrector and select part to lower table
    """
    def __init__(self, cors, field, parent=None, nmax=4):
        super(CorrectorViewer, self).__init__(parent)
        self._nmax  = nmax
        self._field = field
        self._cors  = cors
        self._corlst1 = QtGui.QTreeWidget()
        self._header = dict([("Element", 0), ("Family", 1), ("s [m]", 2),
                             ("Alpha X", 3), ("Alpha Y", 4), ("Beta X", 5),
                             ("Beta Y", 6), ("Phi X", 7), ("Phi Y", 8),
                             ("Eta X", 9)])
        self._twiss = np.zeros((len(self._cors), 8), 'd')
        self._tunes = getTunes(source="database")
        self._corlst1.setColumnCount(len(self._header))
        self._corlst1.setHeaderLabels(
            sorted(self._header, key=self._header.get))
        self._corlst1.header().setStretchLastSection(False)
        prevcell = None
        for i,c in enumerate(self._cors):
            if c.cell and (prevcell is None or c.cell != prevcell.text(0)):
                # a new parent
                prevcell = QtGui.QTreeWidgetItem()
                prevcell.setText(0, c.cell)
                self._corlst1.addTopLevelItem(prevcell)
            it = QtGui.QTreeWidgetItem()
            it.setData(0, Qt.UserRole, i)
            it.setText(self._header["Element"], c.name)
            it.setText(self._header["Family"], c.family)
            it.setText(self._header["s [m]"], "%.3f" % c.sb)
            try:
                tw = getTwiss(c.name, 
                              ["s", "alphax", "alphay", "betax", "betay",
                               "phix", "phiy", "etax"])
                self._twiss[i,:] = tw[0,:]
                it.setText(self._header["Alpha X"], "%.4f" % self._twiss[i,1])
                it.setText(self._header["Alpha Y"], "%.4f" % self._twiss[i,2])
                it.setText(self._header["Beta X"],  "%.4f" % self._twiss[i,3])
                it.setText(self._header["Beta Y"],  "%.4f" % self._twiss[i,4])
                it.setText(self._header["Phi X"],   "%.4f" % self._twiss[i,5])
                it.setText(self._header["Phi Y"],   "%.4f" % self._twiss[i,6])
                it.setText(self._header["Eta X"],   "%.4f" % self._twiss[i,7])
            except:
                it.setDisabled(True)
                pass

            if c.cell:
                prevcell.addChild(it)
            else:
                self._corlst1.addTopLevelItem(it)
                prevcell = it
            for j in range(2, len(self._header)):
                it.setTextAlignment(j, Qt.AlignRight)
        self._corlst1.expandAll()
        for i in range(len(self._header)):
            self._corlst1.resizeColumnToContents(i)
        #self._corlst1.setColumnWidth(0, 150)

        #self.elemlst.setSelectionMode(QAbstractItemView.MultiSelection)
        columns = ['Corrector', 's', 'Alpha', 'Beta',
                   'Phi', "dPhi", "Initial Bump", "Cur. Sp", "dBump",
                   "Final Rb"]
        self.table4 = QTableWidget(0, len(columns))
        #self.table4.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        hdview = QHeaderView(Qt.Horizontal)
        self.table4.setHorizontalHeaderLabels(columns)
        #for i in range(4):
        #    for j in range(len(columns)):
        #        it = QTableWidgetItem()
        #        if j > 0: it.setTextAlignment(
        #            Qt.AlignRight | Qt.AlignVCenter)
        #        if columns[j] != "dKick":
        #            it.setFlags(it.flags() & (~Qt.ItemIsEditable))
        #        self.table4.setItem(i, j, it)
        #self.table4.resizeColumnsToContents()
        #self.table4.horizontalHeader().setStretchLastSection(True)
        #hrow = self.table4.rowHeight(0)
        #htbl = (hrow * 4) + self.table4.horizontalHeader().height() +\
        #    2*self.table4.frameWidth()
        #self.table4.setMinimumHeight(htbl + 10)
        #self.table4.setMaximumHeight(htbl + 15)
        #self.table4.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        #print "Size:", htbl + 10
        self.table4.resize(self.table4.width(), 150)

        splitter = QtGui.QSplitter(Qt.Vertical)
        splitter.addWidget(self._corlst1)
        splitter.addWidget(self.table4)
        vbox1 = QtGui.QVBoxLayout()
        vbox1.addWidget(splitter)
        self.setLayout(vbox1)

        self.connect(self._corlst1, SIGNAL("doubleClicked(QModelIndex)"),
                     self.addCorrector)
        #self.connect(self.src, SIGNAL("returnPressed()"),
        #             self._calc_source)
        #self.connect(self.table4, SIGNAL("cellChanged(int, int)"),
        #             self.updateTable)

        #self.connect(self.table4, SIGNAL("doubleClicked(QModelIndex)"),
        #             self.delCorrector)
        self._x0 = fget(self._cors, "x", handle="setpoint", unitsys=None)
        self._y0 = fget(self._cors, "y", handle="setpoint", unitsys=None)


    def addCorrector(self, idx):
        if not self._corlst1.selectedItems(): return
        #print self._corlst1.itemFromIndex(idx).text(0)
        nrow = self.table4.rowCount()
        if nrow >= self._nmax:
            QtGui.QMessageBox.critical(
                self, "Local Orbit Bump", 
                "ERROR: We need only {0} correctors.".format(self._nmax),
                QtGui.QMessageBox.Ok)
                #self.progress.setValue(0)
            return
        self.table4.setRowCount(nrow+1)
        it0 = self._corlst1.selectedItems()[-1]
        icor, ok = it0.data(0, Qt.UserRole).toInt()
        if icor < 0: return
        newc = self._cors[icor]
        for j in range(self.table4.columnCount()):
            it = QTableWidgetItem()
            if j > 0: it.setTextAlignment(
                Qt.AlignRight | Qt.AlignVCenter)
            header = self.table4.horizontalHeaderItem(j)
            if header.text() != "dBump":
                it.setFlags(it.flags() & (~Qt.ItemIsEditable))
            else:
                it.setData(Qt.DisplayRole, "0")
                it.setData(Qt.UserRole, 0.0)
            self.table4.setItem(nrow, j, it)
        self.table4.item(nrow,0).setData(Qt.UserRole, icor)
        for j,h in [(0, "Element"), (1, "s [m]")]:
            self.table4.item(nrow,j).setData(Qt.DisplayRole,
                                          it0.text(self._header[h]))
        for j in range(self._corlst1.columnCount()):
            it0.setForeground(j, Qt.red)
        it0.setDisabled(True)
        self.emit(SIGNAL("correctorAdded(PyQt_PyObject)"), newc)
        # use initial values

        self.updateTwiss()
        self.updateCorReadings()
        self.table4.resizeColumnsToContents()
        if self.table4.rowCount() == self._nmax:
            #print "All correctors are ready"
            self.emit(SIGNAL("correctorsComplete()"))

    def updateTwiss(self):
        if self._field == "x":
            jl = [self._header[h] for h in ["Alpha X", "Beta X", "Phi X"]]
            nu = self._tunes[0]
        elif self._field == "y":
            jl = [self._header[h] for h in ["Alpha Y", "Beta Y", "Phi Y"]]
            nu = self._tunes[1]
        else:
            raise RuntimeError("unknown cor field {0}".format(self._field))
        #print "index:", jl
        # if rows provided use it, otherwise use all
        for i in range(self.table4.rowCount()):
            elemname = self.table4.item(i,0).data(Qt.DisplayRole).toString()
            it0 = self._corlst1.findItems(
                elemname, Qt.MatchExactly | Qt.MatchRecursive)[0]
            
            self.table4.item(i,2).setText(it0.text(jl[0]))
            self.table4.item(i,3).setText(it0.text(jl[1]))
            self.table4.item(i,4).setText(it0.text(jl[2]))
            self.table4.item(i,4).setData(Qt.UserRole, float(it0.text(jl[2])))

            if i == 0:
                self.table4.item(i,5).setText("0.0")
                self.table4.item(i,5).setData(Qt.UserRole, 0.0)
            else:
                dph, ok = self.table4.item(i-1,5).data(Qt.UserRole).toFloat()
                ph0, ok = self.table4.item(i-1,4).data(Qt.UserRole).toFloat()
                ph1, ok = self.table4.item(i,4).data(Qt.UserRole).toFloat()
                dph = dph + ph1 - ph0
                if ph1 < ph0:
                    dph = dph + 2.0*np.pi*nu
                #print "Updating twiss:", i, dph
                self.table4.item(i,5).setData(Qt.UserRole, dph)
                self.table4.item(i,5).setText("%.5g" % dph)
            icor, ok = self.table4.item(i,0).data(Qt.UserRole).toInt()
            #c = self._cors[icor]
            #kick = self._cors[icor].get(self._field, unitsys=None)
            #self.table4.item(i,6).setData(Qt.UserRole, kick)
            #self.table4.item(i,6).setText("%.5g" % kick)
        #self.updateKickReadings(col=0)

    def clear(self):
        for i in range(self.table4.rowCount()):
            elemname = self.table4.item(i,0).data(Qt.DisplayRole).toString()
            it0 = self._corlst1.findItems(
                elemname, Qt.MatchExactly | Qt.MatchRecursive)[0]
            it0.setDisabled(False)
            for j in range(self._corlst1.columnCount()):
                it0.setForeground(j, Qt.black)
        self.table4.setRowCount(0)
    
    def updateCorReadings(self):
        for i in range(self.table4.rowCount()):
            icor, ok = self.table4.item(i,0).data(Qt.UserRole).toInt()
            cor = self._cors[icor]
            if self._field == "x":
                self.table4.item(i,6).setData(Qt.UserRole, self._x0[icor])
                self.table4.item(i,6).setText("%.5g" % self._x0[icor])
            elif self._field == "y":
                self.table4.item(i,6).setData(Qt.UserRole, self._y0[icor])
                self.table4.item(i,6).setText("%.5g" % self._y0[icor])
            kicksp = cor.get(self._field, handle="setpoint", unitsys=None)
            self.table4.item(i,7).setData(Qt.UserRole, float(kicksp))
            self.table4.item(i,7).setText("%.5g" % kicksp)
            kickrb = cor.get(self._field, handle="readback", unitsys=None)
            self.table4.item(i,9).setData(Qt.UserRole, float(kickrb))
            self.table4.item(i,9).setText("%.5g" % kickrb)


    def updateDbump(self, dkick):
        nrow = min(self.table4.rowCount(), len(dkick))
        for i in range(nrow):
            # dbump column is 8
            it = self.table4.item(i, 8)
            if dkick[i] is None:
                it.setData(Qt.DisplayRole, "")
                it.setData(Qt.UserRole, 0.0)
            else:
                it.setData(Qt.UserRole, float(dkick[i]))
                it.setData(Qt.DisplayRole, "{0}".format(dkick[i]))
        self.updateCorReadings()
        self.table4.resizeColumnsToContents()
        #print "(0,7)", self.table4.item(0, 7).data(Qt.UserRole).toFloat()
        #print "(0,7)", self.table4.item(0, 7).data(Qt.DisplayRole).toFloat()

    def applyKick(self):
        nrow = self.table4.rowCount()
        for i in range(nrow):
            icor, ok = self.table4.item(i,0).data(Qt.UserRole).toInt()
            cor = self._cors[icor]
            # Current SP: 7, dBump 8
            k0, ok = self.table4.item(i, 7).data(Qt.UserRole).toFloat()
            dk, ok = self.table4.item(i, 8).data(Qt.UserRole).toFloat()
            #print "Setting {0} {1}+{2} [A]".format(cor.name, k0, dk)
            cor.put(self._field, k0+dk, unitsys=None)

        # update the final readings
        self.updateCorReadings()

    def getTwiss(self):
        tw = {"s": [], "Alpha": [], "Beta": [],
              "Phi": [], "dPhi": []}
        nrow = self.table4.rowCount()
        for j in range(self.table4.columnCount()):
            header = self.table4.horizontalHeaderItem(j)
            if header.text() not in tw.keys():
                continue
            k = str(header.text())
            for i in range(nrow):
                it = self.table4.item(i, j)
                v0, ok0 = it.data(Qt.UserRole).toFloat()
                v1, ok1 = it.data(Qt.DisplayRole).toFloat()
                if ok0:
                    tw[k].append(v0)
                elif ok1:
                    tw[k].append(v1)
                else:
                    tw[k].append(np.nan)
        return tw

    def selectedCorrectors(self):
        ret = []
        for i in range(self.table4.rowCount()):
            icor, ok = self.table4.item(i,0).data(Qt.UserRole).toInt()
            ret.append(self._cors[icor])
        return ret

    def resetCorrectors(self):
        for i in range(self.table4.rowCount()):
            icor, ok = self.table4.item(i,0).data(Qt.UserRole).toInt()
            cor = self._cors[icor]
            if self._field == "x":
                kick = self._x0[icor]
            elif self._field == "y":
                kick = self._y0[icor]
            cor.put(self._field, kick, unitsys=None)
    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)