class SelectActivities(QDialog): select = Signal() def __init__(self, parent = None): super(SelectActivities, self).__init__(parent) layout = QVBoxLayout(self) self.table = QTableWidget(parent) self.table.setColumnCount(3) self.table.setHorizontalHeaderLabels(["", "Date", "Size"]) self.table.setColumnWidth(0, 25) self.table.setColumnWidth(1, 100) self.table.setColumnWidth(3, 80) layout.addWidget(self.table) self.buttonbox = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonbox.accepted.connect(self.accept) self.buttonbox.rejected.connect(self.reject) self.select.connect(self._select) layout.addWidget(self.buttonbox) self.setMinimumSize(320, 200) def selectActivities(self, antfiles): logger.debug("SelectActivities.selectActivities") self.antfiles = antfiles self.lock = threading.Condition() self.lock.acquire() self.select.emit() logger.debug("SelectActivities.selectActivities: signal emitted") self.lock.wait() self.lock.release() logger.debug("SelectActivities.selectActivities: returning %s selected activities", len(self._selected)) return self._selected def _select(self): logger.debug("SelectActivities._select") self.table.clear() self.table.setRowCount(len(self.antfiles)) for row in range(len(self.antfiles)): f = self.antfiles[row] self.table.setCellWidget(row, 0, QCheckBox(self)) self.table.setItem(row, 1, QTableWidgetItem(f.get_date().strftime("%d %b %Y %H:%M"))) self.table.setItem(row, 2, QTableWidgetItem("{:d}".format(f.get_size()))) result = self.exec_() self._selected = [] if result == QDialog.Accepted: for i in range(len(self.antfiles)): f = self.antfiles[i] cb = self.table.cellWidget(i, 0) if cb.isChecked(): self._selected.append(f) self.lock.acquire() logger.debug("SelectActivities._select: lock acquired") self.lock.notify() self.lock.release()
class MainWindow(QMainWindow): def __init__(self, parent = None): super(MainWindow, self).__init__(parent) self.setWindowTitle('Basic Drawing') self.app = QCoreApplication.instance() self.setGeometry(self.app.myRectangle) st = self.app.style() self.params = ( ('ButtonMargin', st.pixelMetric(QStyle.PM_ButtonMargin)), ('DockWidgetTitleBarButtonMargin', st.pixelMetric(QStyle.PM_DockWidgetTitleBarButtonMargin)), ('ButtonDefaultIndicator', st.pixelMetric(QStyle.PM_ButtonDefaultIndicator)), ('MenuButtonIndicator', st.pixelMetric(QStyle.PM_MenuButtonIndicator)), ('ButtonShiftHorizontal', st.pixelMetric(QStyle.PM_ButtonShiftHorizontal)), ('ButtonShiftVertical', st.pixelMetric(QStyle.PM_ButtonShiftVertical)), ('DefaultFrameWidth', st.pixelMetric(QStyle.PM_DefaultFrameWidth)), ('SpinBoxFrameWidth', st.pixelMetric(QStyle.PM_SpinBoxFrameWidth)), ('ComboBoxFrameWidth', st.pixelMetric(QStyle.PM_ComboBoxFrameWidth)), ('MdiSubWindowFrameWidth', st.pixelMetric(QStyle.PM_MdiSubWindowFrameWidth)), ('MdiSubWindowMinimizedWidth', st.pixelMetric(QStyle.PM_MdiSubWindowMinimizedWidth)), ('LayoutLeftMargin', st.pixelMetric(QStyle.PM_LayoutLeftMargin)), ('LayoutTopMargin', st.pixelMetric(QStyle.PM_LayoutTopMargin)), ('LayoutRightMargin', st.pixelMetric(QStyle.PM_LayoutRightMargin)), ('LayoutBottomMargin', st.pixelMetric(QStyle.PM_LayoutBottomMargin)), ('LayoutHorizontalSpacing', st.pixelMetric(QStyle.PM_LayoutHorizontalSpacing)), ('LayoutVerticalSpacing', st.pixelMetric(QStyle.PM_LayoutVerticalSpacing)), ('MaximumDragDistance', st.pixelMetric(QStyle.PM_MaximumDragDistance)), ('ScrollBarExtent', st.pixelMetric(QStyle.PM_ScrollBarExtent)), ('ScrollBarSliderMin', st.pixelMetric(QStyle.PM_ScrollBarSliderMin)), ('SliderThickness', st.pixelMetric(QStyle.PM_SliderThickness)), ('SliderControlThickness', st.pixelMetric(QStyle.PM_SliderControlThickness)), ('SliderLength', st.pixelMetric(QStyle.PM_SliderLength)), ('SliderTickmarkOffset', st.pixelMetric(QStyle.PM_SliderTickmarkOffset)), ('SliderSpaceAvailable', st.pixelMetric(QStyle.PM_SliderSpaceAvailable)), ('DockWidgetSeparatorExtent', st.pixelMetric(QStyle.PM_DockWidgetSeparatorExtent)), ('DockWidgetHandleExtent', st.pixelMetric(QStyle.PM_DockWidgetHandleExtent)), ('DockWidgetFrameWidth', st.pixelMetric(QStyle.PM_DockWidgetFrameWidth)), ('DockWidgetTitleMargin', st.pixelMetric(QStyle.PM_DockWidgetTitleMargin)), ('MenuBarPanelWidth', st.pixelMetric(QStyle.PM_MenuBarPanelWidth)), ('MenuBarItemSpacing', st.pixelMetric(QStyle.PM_MenuBarItemSpacing)), ('MenuBarHMargin', st.pixelMetric(QStyle.PM_MenuBarHMargin)), ('MenuBarVMargin', st.pixelMetric(QStyle.PM_MenuBarVMargin)), ('ToolBarFrameWidth', st.pixelMetric(QStyle.PM_ToolBarFrameWidth)), ('ToolBarHandleExtent', st.pixelMetric(QStyle.PM_ToolBarHandleExtent)), ('ToolBarItemMargin', st.pixelMetric(QStyle.PM_ToolBarItemMargin)), ('ToolBarItemSpacing', st.pixelMetric(QStyle.PM_ToolBarItemSpacing)), ('ToolBarSeparatorExtent', st.pixelMetric(QStyle.PM_ToolBarSeparatorExtent)), ('ToolBarExtensionExtent', st.pixelMetric(QStyle.PM_ToolBarExtensionExtent)), ('TabBarTabOverlap', st.pixelMetric(QStyle.PM_TabBarTabOverlap)), ('TabBarTabHSpace', st.pixelMetric(QStyle.PM_TabBarTabHSpace)), ('TabBarTabVSpace', st.pixelMetric(QStyle.PM_TabBarTabVSpace)), ('TabBarBaseHeight', st.pixelMetric(QStyle.PM_TabBarBaseHeight)), ('TabBarBaseOverlap', st.pixelMetric(QStyle.PM_TabBarBaseOverlap)), ('TabBarScrollButtonWidth', st.pixelMetric(QStyle.PM_TabBarScrollButtonWidth)), ('TabBarTabShiftHorizontal', st.pixelMetric(QStyle.PM_TabBarTabShiftHorizontal)), ('TabBarTabShiftVertical', st.pixelMetric(QStyle.PM_TabBarTabShiftVertical)), ('ProgressBarChunkWidth', st.pixelMetric(QStyle.PM_ProgressBarChunkWidth)), ('SplitterWidth', st.pixelMetric(QStyle.PM_SplitterWidth)), ('TitleBarHeight', st.pixelMetric(QStyle.PM_TitleBarHeight)), ('IndicatorWidth', st.pixelMetric(QStyle.PM_IndicatorWidth)), ('IndicatorHeight', st.pixelMetric(QStyle.PM_IndicatorHeight)), ('ExclusiveIndicatorWidth', st.pixelMetric(QStyle.PM_ExclusiveIndicatorWidth)), ('ExclusiveIndicatorHeight', st.pixelMetric(QStyle.PM_ExclusiveIndicatorHeight)), ('MenuPanelWidth', st.pixelMetric(QStyle.PM_MenuPanelWidth)), ('MenuHMargin', st.pixelMetric(QStyle.PM_MenuHMargin)), ('MenuVMargin', st.pixelMetric(QStyle.PM_MenuVMargin)), ('MenuScrollerHeight', st.pixelMetric(QStyle.PM_MenuScrollerHeight)), ('MenuTearoffHeight', st.pixelMetric(QStyle.PM_MenuTearoffHeight)), ('MenuDesktopFrameWidth', st.pixelMetric(QStyle.PM_MenuDesktopFrameWidth)), ('CheckListButtonSize', st.pixelMetric(QStyle.PM_CheckListButtonSize)), ('CheckListControllerSize', st.pixelMetric(QStyle.PM_CheckListControllerSize)), ('HeaderMarkSize', st.pixelMetric(QStyle.PM_HeaderMarkSize)), ('HeaderGripMargin', st.pixelMetric(QStyle.PM_HeaderGripMargin)), ('HeaderMargin', st.pixelMetric(QStyle.PM_HeaderMargin)), ('SpinBoxSliderHeight', st.pixelMetric(QStyle.PM_SpinBoxSliderHeight)), ('ToolBarIconSize', st.pixelMetric(QStyle.PM_ToolBarIconSize)), ('SmallIconSize', st.pixelMetric(QStyle.PM_SmallIconSize)), ('LargeIconSize', st.pixelMetric(QStyle.PM_LargeIconSize)), ('FocusFrameHMargin', st.pixelMetric(QStyle.PM_FocusFrameHMargin)), ('FocusFrameVMargin', st.pixelMetric(QStyle.PM_FocusFrameVMargin)), ('IconViewIconSize', st.pixelMetric(QStyle.PM_IconViewIconSize)), ('ListViewIconSize', st.pixelMetric(QStyle.PM_ListViewIconSize)), ('ToolTipLabelFrameWidth', st.pixelMetric(QStyle.PM_ToolTipLabelFrameWidth)), ('CheckBoxLabelSpacing', st.pixelMetric(QStyle.PM_CheckBoxLabelSpacing)), ('RadioButtonLabelSpacing', st.pixelMetric(QStyle.PM_RadioButtonLabelSpacing)), ('TabBarIconSize', st.pixelMetric(QStyle.PM_TabBarIconSize)), ('SizeGripSize', st.pixelMetric(QStyle.PM_SizeGripSize)), ('MessageBoxIconSize', st.pixelMetric(QStyle.PM_MessageBoxIconSize)), ('ButtonIconSize', st.pixelMetric(QStyle.PM_ButtonIconSize)), ('TextCursorWidth', st.pixelMetric(QStyle.PM_TextCursorWidth)), ('TabBar_ScrollButtonOverlap', st.pixelMetric(QStyle.PM_TabBar_ScrollButtonOverlap)), ('TabCloseIndicatorWidth', st.pixelMetric(QStyle.PM_TabCloseIndicatorWidth)), ('TabCloseIndicatorHeight', st.pixelMetric(QStyle.PM_TabCloseIndicatorHeight)), ('CustomBase', st.pixelMetric(QStyle.PM_CustomBase)) ) self.tw = QTableWidget(len(self.params), 2) length = 0 strin = '' for i in range(len(self.params)): item1 = QTableWidgetItem (self.params[i][0]) item2 = QTableWidgetItem (str(self.params[i][1])) self.tw.setItem(i, 0, item1) self.tw.setItem(i, 1, item2) self.setCentralWidget(self.tw) #fm = QFontMetrics(self.tw.font()) fm = QFontMetrics(self.tw.item(1,1).font()) #fm = self.tw.fontMetrics() for param in self.params: l = fm.size(1, self.tr(param[0])).width() if l > length: length = l strin = self.tr(param[0]) print 'MaxWidth: {0}, for string: {1}'.format(length, strin) self.tw.setColumnWidth(0, length) appFont = self.app.font() cellFont = self.tw.item(1,1).font() tableFont = self.tw.font() print appFont print cellFont print tableFont print fm
class AdminWidget(QWidget): """Represents admin panel""" def __init__(self, window): super(AdminWidget, self).__init__(window) self.parentWidget().setWindowTitle("Administartor panel") self.__setupMenu() self.layout = QGridLayout(self) self.user_table = QTableWidget(self) self.user_table.setColumnCount(3) self.user_table.setHorizontalHeaderLabels(["Username", "Blocked", "Password restriction"]) self.user_table.setSelectionBehavior(QAbstractItemView.SelectRows) self.user_table.setSelectionMode(QAbstractItemView.SingleSelection) self.user_table.setColumnWidth(0, 210) self.user_table.setColumnWidth(2, 170) self.user_table.verticalHeader().hide() changePasswordBtn = QPushButton("Change Password") changePasswordBtn.clicked.connect(window.requestPasswordChange) createUserBtn = QPushButton("Add User") createUserBtn.clicked.connect(self._request_new_account) logOutBtn = QPushButton("Logout") logOutBtn.clicked.connect(lambda: (window.app.logOut(), window.hide(), window.requestCredentials())) self.layout.addWidget(self.user_table, 0, 0, 1, 0) self.layout.addWidget(changePasswordBtn, 1, 0) self.layout.addWidget(createUserBtn, 1, 1) self.layout.addWidget(logOutBtn, 1, 2) self.setLayout(self.layout) self.__loadUsers() def __loadUsers(self): """Loads user's data from DB""" users = self.parentWidget().app.getUsers() self.user_table.clearContents() self.user_table.setRowCount(len(users)) for i in range(len(users)): username_item = QTableWidgetItem(users[i].username) username_item.setFlags(username_item.flags() ^ Qt.ItemIsEditable) blocked_checkbox = QCheckBox() if users[i].blocked: blocked_checkbox.setChecked(True) def create_blocked_toggle(checkbox, user): def blocked_toggle(): user.blocked = (1 if checkbox.isChecked() else 0) self.parentWidget().app.updateUser(user) self.__loadUsers() return blocked_toggle blocked_checkbox.toggled.connect(create_blocked_toggle(blocked_checkbox, users[i])) password_restrict_checkbox = QCheckBox() if users[i].restrictions: password_restrict_checkbox.setChecked(True) def create_password_restrict_toggle(checkbox, user): def password_restrict_toggle(): user.restrictions = (1 if checkbox.isChecked() else 0) self.parentWidget().app.updateUser(user) self.__loadUsers() return password_restrict_toggle password_restrict_checkbox.toggled.connect( create_password_restrict_toggle(password_restrict_checkbox, users[i])) self.user_table.setItem(i, 0, username_item) self.user_table.setCellWidget(i, 1, blocked_checkbox) self.user_table.setCellWidget(i, 2, password_restrict_checkbox) def __setupMenu(self): add_account_action = QAction("Add account", self) add_account_action.triggered.connect(self._request_new_account) self.parentWidget().account_menu.addAction(add_account_action) def _request_new_account(self): dialog = None def ok_handler(username): if not 3 <= len(username) <= 20: QMessageBox.critical(dialog, "Error", "Username's length must be between 3 and 20", modal=True) return user = User(username=username) status = self.parentWidget().app.addUser(user) { Core.ERROR_USER_EXISTS: lambda: QMessageBox.critical(dialog, "Error", "Username already exists", modal=True), Core.SUCCESS: lambda: ( self.__loadUsers(), dialog.close() ) }[status]() def cancel_handler(): dialog.close() dialog = AdminWidget.AddAccountDialog(self, ok_handler, cancel_handler) dialog.show() class AddAccountDialog(QDialog): def __init__(self, parent, ok_handler, cancel_handler): super(AdminWidget.AddAccountDialog, self).__init__(parent) self.setWindowTitle("Add account") self.setFixedSize(300, 100) self.setModal(True) self.layout = QGridLayout(self) self.username_label = QLabel(self) self.username_label.setText("Username") self.edit_username = QLineEdit(self) self.buttons = QDialogButtonBox(self) self.buttons.addButton(QDialogButtonBox.Ok) self.buttons.addButton(QDialogButtonBox.Cancel) self.buttons.button(QDialogButtonBox.Ok).setText("Add") self.buttons.button(QDialogButtonBox.Cancel).setText("Cancel") self.buttons.button(QDialogButtonBox.Cancel).clicked.connect(cancel_handler) self.buttons.button(QDialogButtonBox.Ok).clicked.connect(lambda: ok_handler(self.edit_username.text())) self.layout.addWidget(self.username_label, 0, 0) self.layout.addWidget(self.edit_username, 0, 1) self.layout.addWidget(self.buttons, 1, 0, 1, 2, Qt.AlignCenter) self.setLayout(self.layout)
class ui(QWidget): def __init__(self): QWidget.__init__(self) self.setupUI() self.id = 1 self.lines = [] self.editable = True self.des_sort = True self.faker = Factory.create() self.btn_add.clicked.connect(self.add_line) self.btn_del.clicked.connect(self.del_line) self.btn_modify.clicked.connect(self.modify_line) self.btn_select_line.clicked.connect(self.select_line) self.btn_select_single.clicked.connect(self.deny_muti_line) self.btn_sort.clicked.connect(self.sortItem) self.btn_set_header.clicked.connect(self.setheader) self.btn_set_middle.clicked.connect(self.middle) self.table.cellChanged.connect(self.cellchange) self.btn_noframe.clicked.connect(self.noframe) # # Sess = sessionmaker(bind = engine) def setupUI(self): self.setWindowTitle(windowTital) self.resize(640, 480) self.table = QTableWidget(self) self.btn_add = QPushButton(u'增加') self.btn_del = QPushButton(u'删除') self.btn_modify = QPushButton(u'可以编辑') self.btn_select_line = QPushButton(u'选择整行') self.btn_select_single = QPushButton(u'禁止选多行') self.btn_sort = QPushButton(u'以分数排序') self.btn_set_header = QPushButton(u'标头设置') self.btn_set_middle = QPushButton(u'文字居中加颜色') self.btn_noframe = QPushButton(u'取消边框颜色交替') self.spacerItem = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Expanding) self.vbox = QVBoxLayout() self.vbox.addWidget(self.btn_add) self.vbox.addWidget(self.btn_del) self.vbox.addWidget(self.btn_modify) self.vbox.addWidget(self.btn_select_line) self.vbox.addWidget(self.btn_select_single) self.vbox.addWidget(self.btn_sort) self.vbox.addWidget(self.btn_set_header) self.vbox.addWidget(self.btn_set_middle) self.vbox.addWidget(self.btn_noframe) self.vbox.addSpacerItem( self.spacerItem) #可以用addItem也可以用addSpacerItem方法添加,没看出哪里不一样 self.txt = QLabel() self.txt.setMinimumHeight(50) self.vbox2 = QVBoxLayout() self.vbox2.addWidget(self.table) self.vbox2.addWidget(self.txt) self.hbox = QHBoxLayout() self.hbox.addLayout(self.vbox2) self.hbox.addLayout(self.vbox) self.setLayout(self.hbox) self.table.setColumnCount(4) ##设置列数 self.headers = [u'id', u'选择', u'姓名', u'成绩', u'住址'] self.table.setHorizontalHeaderLabels(self.headers) self.show() def add_line(self): self.table.cellChanged.disconnect() row = self.table.rowCount() self.table.setRowCount(row + 1) id = str(self.id) ck = QCheckBox() h = QHBoxLayout() h.setAlignment(Qt.AlignCenter) h.addWidget(ck) w = QWidget() w.setLayout(h) name = self.faker.name() score = str(random.randint(50, 99)) add = self.faker.address() self.table.setItem(row, 0, QTableWidgetItem(id)) self.table.setCellWidget(row, 1, w) self.table.setItem(row, 2, QTableWidgetItem(name)) self.table.setItem(row, 3, QTableWidgetItem(score)) self.table.setItem(row, 4, QTableWidgetItem(add)) self.id += 1 self.lines.append([id, ck, name, score, add]) self.settext(u'自动生成随机一行数据!,checkbox设置为居中显示') self.table.cellChanged.connect(self.cellchange) def del_line(self): removeline = [] for line in self.lines: if line[1].isChecked(): row = self.table.rowCount() for x in range(row, 0, -1): if line[0] == self.table.item(x - 1, 0).text(): self.table.removeRow(x - 1) removeline.append(line) for line in removeline: self.lines.remove(line) self.settext(u'删除在左边checkbox中选中的行,使用了一个笨办法取得行号\n,不知道有没有其他可以直接取得行号的方法!') def modify_line(self): if self.editable == True: self.table.setEditTriggers(QAbstractItemView.NoEditTriggers) self.btn_modify.setText(u'禁止编辑') self.editable = False else: self.table.setEditTriggers(QAbstractItemView.AllEditTriggers) self.btn_modify.setText(u'可以编辑') self.editable = True self.settext(u'设置,是否可以编辑整个表格') def select_line(self): if self.table.selectionBehavior() == 0: self.table.setSelectionBehavior(1) self.btn_select_line.setStyleSheet('background-color:lightblue') else: self.table.setSelectionBehavior(0) self.btn_select_line.setStyleSheet('') self.settext(u'默认时,点击单元格,只可选择一个格,此处设置为可选择整行') def deny_muti_line(self): if self.table.selectionMode() in [2, 3]: self.table.setSelectionMode(QAbstractItemView.SingleSelection) self.btn_select_single.setStyleSheet('background-color:lightblue') else: self.table.setSelectionMode(QAbstractItemView.ExtendedSelection) self.btn_select_single.setStyleSheet('') self.settext(u'点击时会轮换以多行或单行选择,默认是可以同时选择多行') def sortItem(self): if self.des_sort == True: self.table.sortItems(3, Qt.DescendingOrder) self.des_sort = False self.btn_sort.setStyleSheet('background-color:lightblue') self.table.setSortingEnabled(True) # 设置表头可以自动排序 else: self.table.sortItems(3, Qt.AscendingOrder) self.des_sort = True self.btn_sort.setStyleSheet('background-color:lightblue') self.table.setSortingEnabled(False) self.settext(u'点击时会轮换以升序降序排列,但排序时,会使自动列宽失效!') def setheader(self): font = QFont(u'微软雅黑', 12) font.setBold(True) self.table.horizontalHeader().setFont(font) # 设置表头字体 self.table.setColumnWidth(0, 50) self.table.setColumnWidth(1, 50) self.table.setColumnWidth(3, 100) self.table.horizontalHeader().setSectionResizeMode( 2, QHeaderView.Stretch) self.table.horizontalHeader().setStyleSheet( 'QHeaderView::section{background:gray}') self.table.horizontalHeader().setFixedHeight(50) self.table.setColumnHidden(0, True) self.btn_set_header.setStyleSheet('background-color:lightblue') self.settext( u'设置标头字体及字号,隐藏ID列,设置标头除姓名外全部为固定宽度\n,设置姓名列自动扩展宽度,设置标头行高,设置标头背景色') def middle(self): self.btn_set_middle.setStyleSheet('background-color:lightblue') self.table.setStyleSheet('color:green;') row = self.table.rowCount() for x in range(row): for y in range(4): if y != 1: item = self.table.item(x, y) item.setTextAlignment(Qt.AlignCenter) else: pass self.btn_set_middle.setStyleSheet('background-color:lightblue') self.settext(u'将文字居中显示,设置文字颜色') def cellchange(self, row, col): item = self.table.item(row, col) txt = item.text() self.settext(u'第%s行,第%s列 , 数据改变为:%s' % (row, col, txt)) def noframe(self): self.table.setAlternatingRowColors(True) self.table.setFrameStyle(QFrame.NoFrame) self.table.setStyleSheet('color:green;' 'gridline-color:white;' 'border:0px solid gray') self.settext(u'取消表的框线,\n 取消表格内框') def settext(self, txt): font = QFont(u'微软雅黑', 10) self.txt.setFont(font) self.txt.setText(txt)
class CustomWidget(QtGui.QMainWindow): def __init__(self): """ Constructor """ QtGui.QMainWindow.__init__(self) self.name = "Custom widget" self.central_widget = QtGui.QWidget() self.setCentralWidget(self.central_widget) # TODO: This is ugly, improve it self.iconp = JConfig().icons_path self._createLayout() def _createGui(self): """ Subclasses must override this depending on the elements they want to add self._createOutputTree(), self._createOutputTable(), self._createOutputWindow() and add them to the corresponding layouts. """ raise NotImplementedError def _createToolBar(self, name): """ Subclasses need to define the specific Actions """ self.toolbar = self.addToolBar(name) self.toolbar.setMovable(False) def _createLayout(self): """ This creates the basic layout: Buttons & Outputs """ # Layouts (This is a common disposition) main_layout = QtGui.QVBoxLayout() self.button_layout = QtGui.QHBoxLayout() output_layout = QtGui.QVBoxLayout() # You will need to create your buttons # and add them to your layout like this: # self.button_layout.addWidget(button_1) # Output Layout Inner (QSplitter) # Add as many widgets as you please # They will be ordered vertically and # be resizable by the user # self.splitter.addWidget(self.table_label) # self.splitter.addWidget(...) self.splitter = QSplitter(QtCore.Qt.Vertical) # Nested layouts main_layout.addLayout(self.button_layout) output_layout.addWidget(self.splitter) main_layout.addLayout(output_layout) self.central_widget.setLayout(main_layout) def _createOutputWindow(self): """ Some binary analysis commands will output to this. """ self.output_label = QtGui.QLabel('Output') self.output_window = QTextEdit() self.output_window.setFontPointSize(10) self.output_window.setReadOnly(True) # Save it for later use self.output_window.original_textcolor = self.output_window.textColor() def _createOutputTable(self): """ A vanilla QTableWidget. Callbacks modify its properties, like number of columns, etc. """ self.table_label = QtGui.QLabel('Table Output') self.table = QTableWidget() self.table.setColumnCount(3) self.table.setColumnWidth(0, 100) self.table.setColumnWidth(1, 300) self.table.setColumnWidth(2, 300) self.table.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) # Connect signals to slots self.table.customContextMenuRequested.connect(self._tablePopup) self.table.horizontalHeader().sectionDoubleClicked.connect( self._tableHeaderDoubleClicked) self.table.cellDoubleClicked.connect(self._tableCellDoubleClicked) def _createOutputTree(self): """ A QtreeWidget. Initially used to display those pesky dword comparison to immediate values. """ self.tree_label = QtGui.QLabel('Tree Output') self.tree = QTreeWidget() self.tree.setColumnCount(3) self.tree.setColumnWidth(0, 150) self.tree.setColumnWidth(1, 150) self.tree.setColumnWidth(2, 50) # Connect signals to slots self.tree.itemDoubleClicked.connect(self._treeElementDoubleClicked) ################################################################# # GUI Callbacks ################################################################# def _console_output(self, s="", err=False): """ Convenience wrapper """ if err: # Error message err_color = QColor('red') self.output_window.setTextColor(err_color) self.output_window.append(s) # restore original color self.output_window.setTextColor( self.output_window.original_textcolor) else: self.output_window.append(s) def _tableCellDoubleClicked(self, row, col): """ Most of the info displayed in QTableWidgets represent addresses. Default action: try to jump to it. """ it = self.table.item(row, col).text() try: addr = int(it, 16) jump_to_address(addr) except ValueError: self._console_output("[!] That does not look like an address...", err=True) return def _tablePopup(self, pos): """ Popup menu activated clicking the secondary button on the table """ menu = QtGui.QMenu() # Add menu entries delRow = menu.addAction(QIcon(self.iconp + "close.png"), "Delete Row") selItem = menu.addAction(QIcon(self.iconp + "bookmark.png"), "Mark entry") menu.addSeparator() origFunc = menu.addAction(QIcon(self.iconp + "lightning.png"), "Select origin function") destFunc = menu.addAction(QIcon(self.iconp + "flag.png"), "Select destination function") # Get entry clicked action = menu.exec_(self.mapToGlobal(pos)) # Dispatch :) if action == delRow: self.table.removeRow(self.table.currentRow()) elif action == selItem: self.table.currentItem().setBackground(QtGui.QColor('red')) elif action == origFunc: try: addr = self.table.currentItem().text() InfoUI.function_orig_ea = int(addr, 16) except: self._console_output("This does not look like an address...", err=True) elif action == destFunc: try: addr = self.table.currentItem().text() InfoUI.function_dest_ea = int(addr, 16) except: self._console_output("This does not look like an address...", err=True) def _tableHeaderDoubleClicked(self, index): """ Used to sort the contents """ self.table.sortItems(index, order=QtCore.Qt.AscendingOrder) def _treeElementDoubleClicked(self, item, column): """ QTreeWidgetElement callback. Basically it jumps to the selected address in IDA disassembly window. """ try: # Only interested in addresses addr_int = int(item.text(column), 16) jump_to_address(addr_int) # Paint some color item.setBackground(column, QtGui.QColor('green')) except: self._console_output("[!] That does not look like an address...", err=True)
class MainWindow(QDialog): """monkey_linux UI""" def __init__(self,parent=None): super(MainWindow, self).__init__() self.init_conf() self.setParent(parent) common.Log.info("set up ui") self.setup_ui() self.findDeviceAction.triggered.connect(self.get_device_status) self.deleteDeviceAction.triggered.connect(self.del_device) # self.storeButton.clicked.connect(self.set_conf) self.startButton.clicked.connect(self.start) self.stopButton.clicked.connect(self.stop) self.checkLogButton.clicked.connect(self.check) self.monkeyButton.clicked.connect(self.checkMonkeyLog) self.exportButton.clicked.connect(self.exportConf) self.importButton.clicked.connect(self.importConf) self.setAbout.triggered.connect(self.about) self.startTime = datetime.datetime.now() self.secsTime = float(1) * 60 * 60 def setup_ui(self): # main window width hand height # self.setMinimumWidth(600) self.setMaximumWidth(800) self.setMinimumHeight(600) # main window title self.setWindowTitle(static.title) # file menu bar self.menuBar = QMenuBar() self.menuBar.setMaximumHeight(23) # self.menuFile = self.menuBar.addMenu(static.menuFile) # self.importAction = QAction(QIcon(static.importPNG), static.importFile, self) # self.exportAction = QAction(QIcon(static.exportPNG), static.exportFile, self) # self.menuFile.addAction(self.importAction) # self.menuFile.addAction(self.exportAction) self.setEnvActioin = QAction(QIcon(static.setPNG), static.pcSet, self) self.menuSet = self.menuBar.addMenu(static.menuSet) self.menuSet.addAction(self.setEnvActioin) self.setAbout = QAction(QIcon(static.setPNG), static.menuAbout, self) self.setAbout.setStatusTip('About') # 状态栏提示 self.menuHelp = self.menuBar.addMenu(static.menuHelp) self.menuHelp.addAction(self.setAbout) # set all layout self.hbox = QHBoxLayout(self) # device ======== self.topLeft = QFrame(self) self.topLeft.setMaximumSize(218, 300) self.topLeft.setMinimumSize(218, 200) self.topLeft.setFrameShape(QFrame.StyledPanel) self.topLeftLayout = QVBoxLayout(self.topLeft) self.toolBar = QToolBar() # self.androidDeviceAction = QRadioButton('Android', self) # self.androidDeviceAction.setFocusPolicy(Qt.NoFocus) # self.ipDeviceAction = QRadioButton('IP', self) # self.ipDeviceAction.setFocusPolicy(Qt.NoFocus) # self.ipDeviceAction.move(10, 10) # self.ipDeviceAction.toggle() self.findDeviceAction = QAction(QIcon(static.findDevice), static.findDeviceButton, self) self.deleteDeviceAction = QAction(QIcon(static.deleteDevice), static.deleteDeviceButton, self) # self.toolBar.addWidget(self.androidDeviceAction) # self.toolBar.addWidget(self.ipDeviceAction) self.toolBar.addAction(self.findDeviceAction) self.toolBar.addAction(self.deleteDeviceAction) self.deviceLab = QLabel(static.deviceName, self) self.device = QTableWidget(1, 2) self.device.setHorizontalHeaderLabels(['name', 'status']) self.device.setColumnWidth(0, 100) self.device.setColumnWidth(1, 80) self.topLeftLayout.addWidget(self.deviceLab) self.topLeftLayout.addWidget(self.toolBar) self.topLeftLayout.addWidget(self.device) # set button or other for running monkey or not and status of device and log ======== self.topRight = QFrame(self) self.topRight.setFrameShape(QFrame.StyledPanel) self.topRight.setMaximumHeight(40) self.startButton = QPushButton(QIcon(static.startPNG), "") self.stopButton = QPushButton(QIcon(static.stopPNG), "") self.status = QLabel(static.status) self.statusEdit = QLineEdit(self) self.statusEdit.setReadOnly(True) self.statusEdit.setMaximumWidth(80) self.statusEdit.setMinimumWidth(80) self.statusEdit.setText("") # check log self.checkLogButton = QPushButton(static.checkLog) self.checkLogButton.setMaximumHeight(20) self.checkLogButton.setMinimumHeight(20) self.checkLogButton.setMaximumWidth(60) self.selectLog = QLabel(static.selectlog) self.logfile = QComboBox() self.dirlist = os.listdir(os.path.join(DIR, "Result")) for d in self.dirlist: if d != "AutoMonkey.log": self.logfile.insertItem(0, d) self.logfile.setMaximumWidth(150) self.logfile.setMaximumHeight(20) self.logfile.setMinimumHeight(20) self.topLayout = QHBoxLayout(self.topRight) self.topLayout.addWidget(self.startButton) self.topLayout.addWidget(self.stopButton) self.topLayout.addWidget(self.status) self.topLayout.addWidget(self.statusEdit) self.topLayout.addWidget(self.selectLog) self.topLayout.addWidget(self.logfile) self.topLayout.addWidget(self.checkLogButton) # set parameter for monkey ======= self.midRight = QFrame(self) self.midRight.setMaximumSize(555, 200) self.midRight.setMinimumSize(555, 200) self.midRight.setFrameShape(QFrame.StyledPanel) self.midRightLayout = QVBoxLayout(self.midRight) self.subLayout0 = QVBoxLayout() self.subLayout1 = QVBoxLayout() self.subLayout2 = QHBoxLayout() self.subLayout3 = QVBoxLayout() self.subLayout4 = QVBoxLayout() self.subLayout5 = QHBoxLayout() self.subLayout6 = QHBoxLayout() self.toolBar = QToolBar() # self.storeAction = QAction(QIcon(static.storePNG), static.storeButton, self) self.startAction = QAction(QIcon(static.startPNG), static.startButton, self) self.stopAction = QAction(QIcon(static.stopPNG), static.stopButton, self) # self.toolBar.addAction(self.storeAction) self.toolBar.addAction(self.startAction) self.toolBar.addAction(self.stopAction) self.timeLongLbl = QLabel(static.timeString, self) self.timeLong = QLineEdit(self) self.timeLong.setMaximumWidth(100) self.timeLong.setMinimumWidth(100) self.timeLong.setPlaceholderText(static.timeLong) self.timeLongUnit = QLabel("H") self.etSetLbl = QLabel(static.eventTypeSet) self.etSet = QTableWidget(2, 2) self.etSet.setMaximumHeight(150) self.etSet.setHorizontalHeaderLabels(['option', 'value']) self.etSet.horizontalHeader().setStretchLastSection(True) self.etSet.setItem(0, 0, QTableWidgetItem("--throttle")) self.etSet.setItem(0, 1, QTableWidgetItem(str(static.eventType["--throttle"]))) # set event type percent self.etPercentLbl = QLabel(static.eventTpyePercent, self) self.etPercent = QTableWidget(2, 2) self.etPercent.setMaximumHeight(150) self.etPercent.setHorizontalHeaderLabels(['option', 'value']) self.etPercent.horizontalHeader().setStretchLastSection(True) self.etPercent.setItem(0, 0, QTableWidgetItem("--pct-touch")) self.etPercent.setItem(0, 1, QTableWidgetItem(str(static.eventPercent["--pct-touch"]))) self.etPercent.setItem(1, 0, QTableWidgetItem("--pct-motion")) self.etPercent.setItem(1, 1, QTableWidgetItem(str(static.eventPercent["--pct-motion"]))) # self.storeButton = QPushButton(QIcon(static.storePNG), static.storeButton) # self.storeButton.setToolTip(static.storeButton) self.exportButton = QPushButton(QIcon(static.exportPNG), static.exportFile) self.exportButton.setToolTip(static.exportFile) self.importButton = QPushButton(QIcon(static.importPNG), static.importFile) self.importButton.setToolTip(static.importFile) self.subLayout2.addWidget(self.timeLongLbl) self.subLayout2.addWidget(self.timeLong) self.subLayout2.addWidget(self.timeLongUnit) self.subLayout2.addWidget(QLabel(" " * 300)) # self.subLayout2.addWidget(self.storeButton) self.subLayout2.addWidget(self.exportButton) self.subLayout2.addWidget(self.importButton) self.subLayout0.addLayout(self.subLayout2) self.subLayout3.addWidget(self.etSetLbl) self.subLayout3.addWidget(self.etSet) self.subLayout4.addWidget(self.etPercentLbl) self.subLayout4.addWidget(self.etPercent) self.subLayout5.addLayout(self.subLayout0) self.subLayout6.addLayout(self.subLayout3) self.subLayout6.addLayout(self.subLayout4) self.midRightLayout.addLayout(self.subLayout5) self.midRightLayout.addLayout(self.subLayout6) # log ======== self.bottom = QFrame(self) self.bottom.setFrameShape(QFrame.StyledPanel) # log information self.logInfo = QLabel(static.logInfo) # information filter self.logFilter = QLabel(static.logFilter) self.monkeyButton = QPushButton(static.openMonkeyLog) self.combo = QComboBox() for i in range(len(static.logLevel)): self.combo.addItem(static.logLevel[i]) self.combo.setMaximumWidth(55) self.combo.setMaximumHeight(20) self.combo.setMinimumHeight(20) # information details self.bottomLayout = QVBoxLayout(self.bottom) self.subLayout = QHBoxLayout() self.subLayout.addWidget(self.logInfo) for i in range(10): self.subLayout.addWidget(QLabel("")) self.subLayout.addWidget(self.monkeyButton) self.subLayout.addWidget(self.logFilter) self.subLayout.addWidget(self.combo) self.bottomLayout.addLayout(self.subLayout) self.tabwidget = TabWidget() self.tabwidget.setMinimumHeight(100) self.bottomLayout.addWidget(self.tabwidget) # splitter mainWindow ++++++++++++++++++++++++++++++++++++ self.splitter2 = QSplitter(Qt.Vertical) self.splitter2.addWidget(self.topRight) self.splitter2.addWidget(self.midRight) self.splitter0 = QSplitter(Qt.Horizontal) self.splitter0.addWidget(self.topLeft) self.splitter0.addWidget(self.splitter2) self.splitter1 = QSplitter(Qt.Vertical) self.splitter1.addWidget(self.menuBar) self.splitter1.addWidget(self.splitter0) self.splitter1.addWidget(self.bottom) self.hbox.addWidget(self.splitter1) self.setLayout(self.hbox) self.show() def about(self): common.showDialog(static.menuAbout, static.dialogAbout) def init_conf(self): common.Log.info("init monkey conf") with open(monkeyConfFile, "w") as f: f.write("deviceList = []" + "\n") f.write("times = " + static.times + "\n") f.write("--throttle = " + static.eventType["--throttle"] + "\n") f.write("--pct-touch = " + static.eventPercent["--pct-touch"] + "\n") f.write("--pct-motion = " + static.eventPercent["--pct-motion"] + "\n") def setup_env(self): pass def _set_eventType(self, confFile): try: option = self.etSet.item(0, 0).text() value = self.etSet.item(0, 1).text() if value > "0": with open(confFile, 'a+') as f: f.write(option + " = " + value + "\n") except AttributeError, e: pass
class CustomWidget(QtGui.QMainWindow): def __init__(self): """ Constructor """ QtGui.QMainWindow.__init__(self) self.name = "Custom widget" self.central_widget = QtGui.QWidget() self.setCentralWidget(self.central_widget) # TODO: This is ugly, improve it self.iconp = JConfig().icons_path self._createLayout() def _createGui(self): """ Subclasses must override this depending on the elements they want to add self._createOutputTree(), self._createOutputTable(), self._createOutputWindow() and add them to the corresponding layouts. """ raise NotImplementedError def _createToolBar(self, name): """ Subclasses need to define the specific Actions """ self.toolbar = self.addToolBar(name) self.toolbar.setMovable(False) def _createLayout(self): """ This creates the basic layout: Buttons & Outputs """ # Layouts (This is a common disposition) main_layout = QtGui.QVBoxLayout() self.button_layout = QtGui.QHBoxLayout() output_layout = QtGui.QVBoxLayout() # You will need to create your buttons # and add them to your layout like this: # self.button_layout.addWidget(button_1) # Output Layout Inner (QSplitter) # Add as many widgets as you please # They will be ordered vertically and # be resizable by the user # self.splitter.addWidget(self.table_label) # self.splitter.addWidget(...) self.splitter = QSplitter(QtCore.Qt.Vertical) # Nested layouts main_layout.addLayout(self.button_layout) output_layout.addWidget(self.splitter) main_layout.addLayout(output_layout) self.central_widget.setLayout(main_layout) def _createOutputWindow(self): """ Some binary analysis commands will output to this. """ self.output_label = QtGui.QLabel('Output') self.output_window = QTextEdit() self.output_window.setFontPointSize(10) self.output_window.setReadOnly(True) # Save it for later use self.output_window.original_textcolor = self.output_window.textColor() def _createOutputTable(self): """ A vanilla QTableWidget. Callbacks modify its properties, like number of columns, etc. """ self.table_label = QtGui.QLabel('Table Output') self.table = QTableWidget() self.table.setColumnCount(3) self.table.setColumnWidth(0, 100) self.table.setColumnWidth(1, 300) self.table.setColumnWidth(2, 300) self.table.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) # Connect signals to slots self.table.customContextMenuRequested.connect(self._tablePopup) self.table.horizontalHeader().sectionDoubleClicked.connect(self._tableHeaderDoubleClicked) self.table.cellDoubleClicked.connect(self._tableCellDoubleClicked) def _createOutputTree(self): """ A QtreeWidget. Initially used to display those pesky dword comparison to immediate values. """ self.tree_label = QtGui.QLabel('Tree Output') self.tree = QTreeWidget() self.tree.setColumnCount(3) self.tree.setColumnWidth(0, 150) self.tree.setColumnWidth(1, 150) self.tree.setColumnWidth(2, 50) # Connect signals to slots self.tree.itemDoubleClicked.connect(self._treeElementDoubleClicked) ################################################################# # GUI Callbacks ################################################################# def _console_output(self, s = "", err = False): """ Convenience wrapper """ if err: # Error message err_color = QColor('red') self.output_window.setTextColor(err_color) self.output_window.append(s) # restore original color self.output_window.setTextColor(self.output_window.original_textcolor) else: self.output_window.append(s) def _tableCellDoubleClicked(self, row, col): """ Most of the info displayed in QTableWidgets represent addresses. Default action: try to jump to it. """ it = self.table.item(row, col).text() try: addr = int(it, 16) jump_to_address(addr) except ValueError: self._console_output("[!] That does not look like an address...", err = True) return def _tablePopup(self, pos): """ Popup menu activated clicking the secondary button on the table """ menu = QtGui.QMenu() # Add menu entries delRow = menu.addAction(QIcon(self.iconp + "close.png"), "Delete Row") selItem = menu.addAction(QIcon(self.iconp + "bookmark.png"), "Mark entry") menu.addSeparator() origFunc = menu.addAction(QIcon(self.iconp + "lightning.png"), "Select origin function") destFunc = menu.addAction(QIcon(self.iconp + "flag.png"), "Select destination function") # Get entry clicked action = menu.exec_(self.mapToGlobal(pos)) # Dispatch :) if action == delRow: self.table.removeRow(self.table.currentRow()) elif action == selItem: self.table.currentItem().setBackground(QtGui.QColor('red')) elif action == origFunc: try: addr = self.table.currentItem().text() InfoUI.function_orig_ea = int(addr, 16) except: self._console_output("This does not look like an address...", err = True) elif action == destFunc: try: addr = self.table.currentItem().text() InfoUI.function_dest_ea = int(addr, 16) except: self._console_output("This does not look like an address...", err = True) def _tableHeaderDoubleClicked(self, index): """ Used to sort the contents """ self.table.sortItems(index, order = QtCore.Qt.AscendingOrder) def _treeElementDoubleClicked(self, item, column): """ QTreeWidgetElement callback. Basically it jumps to the selected address in IDA disassembly window. """ try: # Only interested in addresses addr_int = int(item.text(column), 16) jump_to_address(addr_int) # Paint some color item.setBackground(column, QtGui.QColor('green')) except: self._console_output("[!] That does not look like an address...", err = True)