SaltyCrane Blog — Notes on JavaScript and web development

More example code for PyQt 4.2

Here is some more example code for PyQt 4.2.

################################################################
################################################################
def main():
    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(True)
    form = StartForm()
    form.show()
    report = ReportWindow()
    app.connect(form, SIGNAL("okClicked"),
                report.create)
    sys.exit(app.exec_())

################################################################
################################################################
class StartForm(QWidget):
    def __init__(self, *args):
        QWidget.__init__(self, *args)

        # position the form on the screen
        self.move(1500, 50)

        # date box
        self.label_date = QLabel()
        self.label_date.setText("Set date of last audit:")
        default = datetime.date.today() - datetime.timedelta(DEFAULT_DAYS_FROM_LAST_AUDIT)
        self.datebox = QDateEdit(QDate(default.year, default.month, default.day))

        # buttons
        spacer = QSpacerItem(20,40,QSizePolicy.Minimum,QSizePolicy.Expanding)
        self.button_ok = QPushButton()
        self.button_ok.setText("OK")
        self.button_ok.setDefault(True)
        button_cancel = QPushButton()
        button_cancel.setText("Cancel")

        # layout
        layout_right = QVBoxLayout(self)
        layout_right.addWidget(self.label_date)
        layout_right.addWidget(self.datebox)
        layout_right.addItem(spacer)
        layout_right.addWidget(self.button_ok)
        layout_right.addWidget(button_cancel)

        # connections
        self.connect(button_cancel, SIGNAL("clicked(bool)"),
                    self.close)
        self.connect(self.button_ok, SIGNAL("clicked(bool)"),
                    self.ok_clicked)

    def ok_clicked(self):
        self.label_date.setText("Getting eventlog data...")
        year = self.datebox.date().year()
        month = self.datebox.date().month()
        day = self.datebox.date().day()
        delta = datetime.date.today() - datetime.date(int(year),int(month),int(day))
        self.emit(SIGNAL("okClicked"), delta.days)
        self.close()

################################################################
################################################################
class ReportWindow(QWidget):
    def __init__(self, *args):
        QWidget.__init__(self, *args)
        self.cbUsers = QCheckBox("Hide SYSTEM users")
        self.cbSorting = QCheckBox("Sorting enabled")
        self.tableview = EventlogTableView()

        vlayout = QVBoxLayout()
        vlayout.addWidget(self.cbUsers)
        vlayout.addWidget(self.cbSorting)
        vlayout.addWidget(self.tableview)
        self.setLayout(vlayout)
        self.setGeometry(100,100,750,550)

        # connections
        self.connect(self.cbUsers, SIGNAL("stateChanged(int)"),
                     self.cbUsersChanged)
        self.connect(self.cbSorting, SIGNAL("stateChanged(int)"),
                     self.cbSortingChanged)

    def create(self, ndays):
        """ Run dumpel.exe, parse and show the results in a table """
        ep = EventlogParser()
        logdata = ep.parseLog(ndays)
        model = EventlogTableModel(logdata, self)
        self.tableview.setModel(model)
        self.tableview.formatData()
        self.show()

    def cbUsersChanged(self):
        state = self.cbUsers.checkState()
        print "state= " + str(state)
        if state == 0:
            self.table.show_system_users()
        elif state == 2:
            self.table.hide_system_users()

    def cbSortingChanged(self):
        state = self.cbSorting.checkState()
        if state == 0:
            self.table.setSortingEnabled(False)
        elif state == 2:
            self.table.setSortingEnabled(True)

################################################################
################################################################
class EventlogTableView(QTableView):
    def __init__(self, *args):
        QTableView.__init__(self, *args)

    def formatData(self):
        """ Formats the data in the table view """
        self.resizeColumnsToContents()

        # format items
        model = self.model()
        self.nrows = model.rowCount(self)
        self.ncols = model.columnCount(self)
        for i in xrange(self.nrows):
            for j in xrange(self.ncols):
                index = model.index(i, j)

################################################################
################################################################
class EventlogTableModel(QAbstractTableModel):
    def __init__(self, datain, parent=None):
        QAbstractTableModel.__init__(self, parent)
        self.logdata = datain

    def rowCount(self, parent):
        return len(self.logdata)

    def columnCount(self, parent):
        return len(self.logdata[0])

    def data(self, index, role):
        if not index.isValid():
            return QVariant()
        elif role != Qt.DisplayRole:
            return QVariant()
        return QVariant(self.logdata[index.row()][index.column()])

################################################################
################################################################
class EventlogParser:
    def __init__(self):
        pass

    def parseLog(self, ndays):
        """ Runs dumpel.exe and stores the results in a data structure
            Example dumpel output:
                3/14/2006    1:00:51 PM    8    1    515    Security    NT AUTHORITY\SYSTEM        ANC9PLT561    Win
            Returns a 2-dimensional list
        """
        os.system("dumpel -f dumpel_results.txt -l security -d %s" % ndays)
        fin = open("dumpel_results.txt", "r")
        data = []
        for line in fin.readlines():
            items = re.split(r'\t+', line, maxsplit=8)

            # date processing
            items[0] = format_datetime(items[0], items[1])

            # success/failure processing
            if items[2] == "8":
                items[2] = "Success"
            elif items[2] == "16":
                items[2] = "Failure"
            else:
                items[2] = "Unknown"

            # event processing
            event = items[4]
            try:
                desc = event_desc[event]
            except:
                desc = 'need to look up this event id'
            items[4] = event + ": " + desc

            # user processing
            (dom, user) = re.split(r"\\", items[6])
            items[6] = user

            # delete unused columns
            items[7:8] = []
            items[5:6] = []
            items[3:4] = []

            data.append(items)
        print "Parse sucessful.\n"
        return data 

Comments


#1 reza commented on :

I couldn't Run this module I added necessary Imports but It doesn't work. I have PyQt4 and Python 2.7 would you edit it ?