def __init__(self, *args, **kwargs): super(FlatTabWidget, self).__init__(*args, **kwargs) self.setupUi() self.normal_color = ResourceLoader().qt_color_sub_text self.active_color = ResourceLoader().qt_color_text self.currentSelection = 0 self.lineMorph = QPropertyAnimation() self.pages = [] self.enqueueSeparatorRepaint = True self.animatePageChange = True self.customSW = None self.detachCustomStackedWidget = False def scrolledUp(): if self.currentSelection - 1 < 0 or len(self.pages) == 0: return self.scrolledUp.emit() item = self.pages[self.currentSelection - 1] if item.label != None: self.setCurrentTab(self.currentSelection - 1) self.TabBarContainer.scrolledUp.connect(scrolledUp) def scrolledDown(): if self.currentSelection + 1 >= len(self.pages) or len(self.pages) == 0: return self.scrolledDown.emit() item = self.pages[self.currentSelection + 1] if item.label != None: self.setCurrentTab(self.currentSelection + 1) self.TabBarContainer.scrolledDown.connect(scrolledDown)
def api(self, params): # 1).获取查询参数 param = self.input_search.text() # 2).查询数据 page = params['page'] data = { 'head': [ {'key': 'sn', 'label': '编号'}, {'key': 'type', 'label': '类型'}, {'key': 'check', 'label': '审核'}, {'key': 'content', 'label': '类容'}, ], 'data': [ { 'sn': {'value': '001', 'type': 'string'}, 'type': {'value': '警告', 'text_color': ResourceLoader().qt_color_warning, 'border_color': ResourceLoader().qt_color_warning, 'font': ResourceLoader().qt_font_text_tag, 'type': 'tag'}, 'check': {'value': 1, 'type': 'checkbox', 'size': 20 }, 'content': {'value': '设备离线', 'type': 'string'}, }, { 'sn': {'value': '002', 'type': 'string'}, 'type': {'value': '正常', 'text_color': ResourceLoader().qt_color_success, 'border_color': ResourceLoader().qt_color_success, 'font': ResourceLoader().qt_font_text_tag, 'type': 'tag'}, 'check': {'value': 0, 'type': 'checkbox', 'size': 20}, 'content': {'value': '设备正常', 'type': 'string'}, } ] } return {'total': 100, 'data': data}
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHints(QPainter.SmoothPixmapTransform) rect = self.rect() w = rect.width() h = rect.height() # 绘制加载信息 painter.save() painter.setFont(ResourceLoader().qt_font_text_xs) painter.setPen(ResourceLoader().qt_color_sub_text) _text_rect = calculate_text_rect('正在努力加载', painter=painter) text_rect = calculate_middle_rect(rect, width=_text_rect.width(), height=_text_rect.height()) painter.translate(QPoint(12, 0)) painter.drawText(text_rect, Qt.TextSingleLine, '正在努力加载') painter.restore() # 绘制加载图标 x2 = w / 2 - text_rect.width() / 2 - 16 y2 = h / 2 painter.save() painter.translate(x2, y2) self.loading_rotate += 14 painter.rotate(self.loading_rotate % 360) # icon = qtawesome.icon('fa5s.spinner', color=ResourceLoader().qt_color_sub_text) icon = qtawesome.icon('mdi.loading', color=ResourceLoader().qt_color_sub_text) icon_pixmap = icon.pixmap(QSize(24, 24)) painter.drawPixmap(QRect(-12, -12, 24, 24), icon_pixmap) painter.restore() QWidget.paintEvent(self, event)
def updateTag(self): if self.model.state == State.on: self.tag.text = "在线" self.tag.padding_h = 4 self.tag.padding_v = 2 self.tag.text_color = ResourceLoader().qt_color_tag_online self.tag.border_color = ResourceLoader().qt_color_tag_online else: self.tag.text = "离线" self.tag.padding_h = 4 self.tag.padding_v = 2 self.tag.text_color = ResourceLoader().qt_color_tag_offline self.tag.border_color = ResourceLoader().qt_color_tag_offline
def set_ui(self): # 搜索栏 label_icon_search = QLabel() label_icon_search.setPixmap(qtawesome.icon('fa5s.search', color=ResourceLoader().qt_color_sub_text).pixmap(QSize(18, 18))) label_icon_search.setFixedSize(20, 20) self.input_search = BaseLineEdit(leftWidget=label_icon_search) self.input_search.setFixedHeight(32) self.input_search.setLeftRightLayoutMargin(10, 10) self.input_search.setPlaceholderText("输入查询条件") self.btn_search = QPushButton() self.btn_search.setProperty("type", 1) self.btn_search.setText("查询") self.btn_search.clicked.connect(self.search) self.btn_reset = QPushButton() self.btn_reset.setProperty("type", 1) self.btn_reset.setText("重置") self.btn_reset.clicked.connect(self.reset) self.separator1 = Separator(self) self.separator1.setFixedHeight(2) # 表格 self.tableView = BaseTableView(self) self.tableView.setObjectName("tableView") self.separator2 = Separator(self) self.separator2.setFixedHeight(2) # 分页栏 self.paginationBar1 = CPaginationBar(self, totalPages=20) self.paginationBar1.setInfos('共 400 条') self.paginationBar1.setJumpWidget(True) self.paginationBar1.pageChanged.connect(lambda page: self.model.fetchData(page=page - 1))
def editorEvent(self, event: QtCore.QEvent, model: QtCore.QAbstractItemModel, option: 'QStyleOptionViewItem', index: QtCore.QModelIndex) -> bool: decorationRect = option.rect if event.type() == QEvent.MouseButtonPress: item = index.model().data(index, Qt.UserRole) if isinstance(item, QVariant): return QStyledItemDelegate.editorEvent(self, event, model, option, index) type = item['type'] value = item['value'] if type == 'device_activity': text_rect = calculate_text_rect( value['device'], font=ResourceLoader().qt_font_text_xs) if calculate_middle_rect(decorationRect, text_rect.width(), text_rect.height(), x=110, y=15).contains(event.pos()): print('点击了设备{device}'.format(device=value['device'])) return QStyledItemDelegate.editorEvent(self, event, model, option, index)
def paint(self, painter: QtGui.QPainter, option: 'QStyleOptionViewItem', index: QtCore.QModelIndex) -> None: viewOption = QStyleOptionViewItem(option) self.initStyleOption(viewOption, index) QStyledItemDelegate.paint(self, painter, viewOption, index) item = index.model().data(index, Qt.UserRole) if isinstance(item, QVariant): return value = item['value'] type = item['type'] if type == 'checkbox': # 数据转换 value = True if value == 1 else 0 # 绘制单选框 checkBoxStyle = QStyleOptionButton() checkBoxStyle.state = QStyle.State_On if value else QStyle.State_Off checkBoxStyle.state |= QStyle.State_Enabled # 计算位置 size = item['size'] rect = calculate_middle_rect(option.rect, size, size) checkBoxStyle.rect = rect checkBox = QCheckBox() QApplication.style().drawPrimitive(QStyle.PE_IndicatorCheckBox, checkBoxStyle, painter, checkBox) if type == 'tag': painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHints(QPainter.SmoothPixmapTransform) path = QPainterPath() # 绘制文本 self.font = ResourceLoader().qt_font_text_tag text_color = item['text_color'] border_color = item['border_color'] text = value padding_v = 2 padding_h = 4 border_radius = 2 border_width = 1 painter.setFont(item['font']) painter.setPen(text_color) fm = QFontMetrics(painter.font()) w = fm.width(text) h = fm.height() # 计算位置 rect = calculate_middle_rect(option.rect, w + padding_h * 2, h + padding_v * 2) rectf = QRectF(rect.x(), rect.y(), rect.width(), rect.height()) painter.drawText( QRect(rectf.x() + padding_h, rectf.y() + padding_v, w, h), Qt.TextWordWrap, text) # 绘制边框 path.addRoundedRect(rectf, border_radius, border_radius) painter.strokePath(path, QPen(border_color, border_width))
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHints(QPainter.SmoothPixmapTransform) rect = self.rect() # 绘制文本 painter.save() painter.setFont(ResourceLoader().qt_font_text_xs) painter.setPen(ResourceLoader().qt_color_sub_text) _text_rect = calculate_text_rect('--- 我是有底线的 ---', painter=painter) text_rect = calculate_middle_rect(rect, width=_text_rect.width(), height=_text_rect.height()) painter.drawText(text_rect, Qt.TextSingleLine, '--- 我是有底线的 ---') painter.restore() QWidget.paintEvent(self, event)
def paintEvent(self, event) -> None: super(ToolTip, self).paintEvent(event) x = self.rect().x() + self._anchor_width y = self.rect().y() + self._anchor_width w = self.rect().width() - self._anchor_width * 2 h = self.rect().height() - self._anchor_width * 2 # 背景 painter = QPainter(self) path = QPainterPath() path.addRoundedRect(QRectF(x, y, w, h), 4, 4) # 画锚 if self._direction == ToolTip.TOP: x1 = x + w / 2 - self._anchor_width y1 = y + h x2 = x + w / 2 + self._anchor_width y2 = y + h x3 = x + w / 2 y3 = y + h + self._anchor_width path.moveTo(x1, y1) path.lineTo(x2, y2) path.lineTo(x3, y3) elif self._direction == ToolTip.BOTTOM: x1 = x + w / 2 - self._anchor_width y1 = y x2 = x + w / 2 + self._anchor_width y2 = y x3 = x + w / 2 y3 = y - self._anchor_width path.moveTo(x1, y1) path.lineTo(x2, y2) path.lineTo(x3, y3) elif self._direction == ToolTip.RIGHT: x1 = x y1 = y + h / 2 - self._anchor_width x2 = x y2 = y + h / 2 + self._anchor_width x3 = x - self._anchor_width y3 = y + h / 2 path.moveTo(x1, y1) path.lineTo(x2, y2) path.lineTo(x3, y3) elif self._direction == ToolTip.LEFT: x1 = x + w y1 = y + h / 2 - self._anchor_width x2 = x + w y2 = y + h / 2 + self._anchor_width x3 = x + w + self._anchor_width y3 = y + h / 2 path.moveTo(x1, y1) path.lineTo(x2, y2) path.lineTo(x3, y3) painter.fillPath(path, ResourceLoader().qt_color_separator_dark)
def show(type=0, msg='空对话框', confirm=None, cancel=None): if type == SysDialog.INFO: message = QMessageBox(QMessageBox.Information, "消息提示框", msg) qyes = message.addButton("确定", QMessageBox.YesRole) message.setWindowIcon(ResourceLoader().qt_icon_project_ico) if confirm: qyes.clicked.connect(confirm) message.exec_() elif type == SysDialog.WARN: message = QMessageBox(QMessageBox.Warning, "警告提示框", msg) qyes = message.addButton("确定", QMessageBox.YesRole) if confirm: qyes.clicked.connect(confirm) message.setWindowIcon(ResourceLoader().qt_icon_project_ico) message.exec_() elif type == SysDialog.WARN_PROMOT: message = QMessageBox(QMessageBox.Warning, "警告确认框", msg) qyes = message.addButton("确定", QMessageBox.YesRole) qno = message.addButton("取消", QMessageBox.NoRole) message.setWindowIcon(ResourceLoader().qt_icon_project_ico) if cancel: qno.clicked.connect(cancel) if confirm: qyes.clicked.connect(confirm) message.exec_() elif type == SysDialog.ERROR: message = QMessageBox(QMessageBox.Critical, "错误提示框", msg) qyes = message.addButton("确定", QMessageBox.YesRole) message.setWindowIcon(ResourceLoader().qt_icon_project_ico) if confirm: qyes.clicked.connect(confirm) message.exec_() elif type == SysDialog.PROMOT: message = QMessageBox(QMessageBox.Question, "确认提示框", msg) qyes = message.addButton("确定", QMessageBox.YesRole) qno = message.addButton("取消", QMessageBox.NoRole) if cancel: qno.clicked.connect(cancel) if confirm: qyes.clicked.connect(confirm) message.setWindowIcon(ResourceLoader().qt_icon_project_ico) message.exec_()
class DeviceList(BaseView): devices = [ CardModel(icon=ResourceLoader().render_pixmap('device_list_current.png'), sn='007', name='MM-370C', state=State.on, active='2020/11/16 11:24'), CardModel(icon=ResourceLoader().render_pixmap('device_list_current.png'), sn='011', name='MM-370C', state=State.off, active='2020/11/15 10:24'), CardModel(icon=ResourceLoader().render_pixmap('device_list_current.png'), sn='020', name='MM-370C', state=State.off, active='2020/11/15 15:24'), ] def __init__(self, *args, **kwargs): super(DeviceList, self).__init__(*args, **kwargs) self.procedure() def set_ui(self): self.grid = GridLayout() self.grid.fixed_width = DeviceCard.fixed_width self.grid.fixed_height = DeviceCard.fixed_height cards = self.create_cards() QTimer.singleShot(0, lambda: self.grid.load(cards)) def create_cards(self): cards = [] for device in self.devices: card = DeviceCard(self.grid.center_widget, model=device) card.clicked.connect(self.open_drawer) cards.append(card) return cards def place(self): layout = QHBoxLayout(self) layout.addWidget(self.grid) def open_drawer(self): if not hasattr(self, 'drawer'): # 编写一个可以查找最外层的BaseActivity实例 self.drawer = Drawer(self.parent().parent(), stretch=0.5, direction=Drawer.RIGHT, popup=False) self.drawer_widget = DeviceDrawer(self.drawer) self.drawer.setWidget(self.drawer_widget) QTimer.singleShot(0, lambda :self.drawer.show())
def setupUi(self): # 横向布局 layout = QHBoxLayout(self) layout.setSpacing(6) layout.setContentsMargins(0, 0, 0, 0) # 总数据量统计 self.labelInfos = QLabel(self, visible=False, alignment=Qt.AlignCenter, objectName='CPaginationBar_labelInfos') # 上一页按钮 self.buttonPrevious = QPushButton( qtawesome.icon('mdi.chevron-left', color=ResourceLoader().qt_color_text), '', self, enabled=False, visible=False, clicked=self._doPageTurning, objectName='CPaginationBar_buttonPrevious') self.buttonPrevious.setIconSize(QSize(18, 18)) # 下一页按钮 self.buttonNext = QPushButton(qtawesome.icon( 'mdi.chevron-right', color=ResourceLoader().qt_color_text), '', self, enabled=False, visible=False, clicked=self._doPageTurning, objectName='CPaginationBar_buttonNext') self.buttonNext.setIconSize(QSize(18, 18)) # 跳转控件 self.paginationJumpBar = _CPaginationJumpBar( 1, self, visible=False, objectName='CPaginationBar_paginationJumpBar') self.paginationJumpBar.valueChanged.connect(self._doJump)
def __init__(self, *args, **kwargs): super(CustomWidget, self).__init__(*args, **kwargs) layout = QHBoxLayout(self) layout.setSpacing(0) label = QLabel() label.setPixmap( qtawesome.icon('mdi.information-variant', color=ResourceLoader().qt_color_text).pixmap( QSize(28, 28))) label2 = QLabel() label2.setText("这是一个自定义提示") layout.addWidget(label) layout.addWidget(label2)
def show(self, waiting_info: str = "加载中,请稍后"): ''' 等待对话框 ''' if not hasattr(self, 'dialog'): self.dialog = QDialog(None, Qt.FramelessWindowHint) self.dialog.setWindowFlags(Qt.Window | Qt.FramelessWindowHint | Qt.Tool | Qt.WindowSystemMenuHint | Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint) self.dialog.resize(200, 40) self.dialog.layout = QHBoxLayout(self.dialog) self.dialog.label = QLabel(waiting_info) self.dialog.label.setFont(ResourceLoader().qt_font_text_xs) self.dialog.layout.addWidget(self.dialog.label, alignment=Qt.AlignCenter) self.dialog.exec_()
def __init__(self, *args, model: CardModel, **kwargs): super(DeviceCard, self).__init__(*args, **kwargs) self.model = model self.setNormalColor(ResourceLoader().qt_color_background_light) self.setHoverColor(ResourceLoader().qt_color_background_light) self.setPressColor(ResourceLoader().qt_color_background) self.setChoking(4) self.setRadius(5, 10) self.hover_speed = 10 self.title_font = ResourceLoader().qt_font_text self.body_font = ResourceLoader().qt_font_text_xss self.title_color = ResourceLoader().qt_color_text self.body_color = ResourceLoader().qt_color_primary_light # 添加状态标签 self.tag = Tag(self) self.updateTag() self.show()
def start(): app = QSingleApplication("zzclient", sys.argv) # 异常捕获 os.makedirs(Config().except_path, exist_ok=True) sys.excepthook = cgitb.Hook(1, Config().except_path, 5, sys.stderr, '') if app.isRunning(): # 激活窗口 app.sendMessage('show', 1000) else: # 窗口关闭程序退出 app.setQuitOnLastWindowClosed(True) # 应用图标 app.setWindowIcon(ResourceLoader().qt_icon_project_ico) # 设置主题样式 Theme.load() # 设置字体 # fontDB = QFontDatabase() # fontDB.addApplicationFont(':/font/Roboto-Regular.ttf') # app.setFont(QFont('Roboto')) # 设置雅黑字体 app.setFont(ResourceLoader.load_app_font()) # 图标字体 ResourceLoader.load_icon_font() # 加载模块 ResourceLoader.load_modules() # 创建窗体 window = HomePage() window.resize(1024 ,768) # 样式注入器 ConnectStyleSheetInspector(main_window=window, shortcut=QKeySequence(Qt.Key_Tab)) # 计算居中显示的位置 desktop = QDesktopWidget().availableGeometry() width = (desktop.width() - window.width()) / 2 height = (desktop.height() - window.height()) / 2 app.setActivationWindow(window) window.show() window.move(width, height) sys.exit(app.exec_())
Window { background-color: #282C34; } ''' class Window(QWidget): def __init__(self, *args, **kwargs): super(Window, self).__init__(*args, **kwargs) self.resize(500, 500) self.setStyleSheet(Style) layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) QTimer.singleShot(400, lambda: Toast.showTip("这是一条提示")) QTimer.singleShot(2000, lambda: Toast.showTip("这是一条提示")) def closeEvent(self, a0: QtGui.QCloseEvent) -> None: Bloc_App().app_closed.emit() if __name__ == '__main__': app = QApplication(sys.argv) Theme.load() app.setFont(ResourceLoader.load_app_font()) window = Window() window.show() sys.exit(app.exec_())
def __init__(self, *args, **kwargs): super(Window, self).__init__(*args, **kwargs) self.resize(500, 500) layout = QVBoxLayout() layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) self.setLayout(layout) navbutton = NavButton() navbutton.setObjectName('NavButton_{name}'.format(name='name')) navbutton.setFixedHeight(80) navbutton.setFixedWidth(94) navbutton.setShowText('你好') navbutton.setShowIcon(True) navbutton.setPaddingLeft(0) navbutton.setPaddingRight(0) navbutton.setPaddingTop(12) navbutton.setPaddingBottom(4) navbutton.setIconNormal( QPixmap(':icon/{icon}'.format(icon='navbar_home.png'))) navbutton.setIconCheck( QPixmap(':icon/{icon}'.format(icon='navbar_home.png'))) navbutton.setIconHover( QPixmap(':icon/{icon}'.format(icon='navbar_home.png'))) navbutton.setTextAlign(TextAlign_Center) navbutton.setFont(ResourceLoader().qt_font_text_xs) navbutton.setIconSize(QSize(34, 34)) navbutton.setIconPosition(IconPosition_Top) navbutton.setNormalBgColor(QColor('transparent')) navbutton.setHoverBgColor(QColor('transparent')) navbutton.setCheckBgColor(QColor('transparent')) navbutton.setNormalTextColor(QColor('#CDCDCD')) navbutton.setHoverTextColor(QColor('#FFFEFE')) navbutton.setCheckTextColor(QColor('#FFFEFE')) layout.addWidget(navbutton) navbutton = NavButton() navbutton.setObjectName('NavButton_{name}'.format(name='name')) navbutton.setFixedHeight(80) navbutton.setFixedWidth(94) navbutton.setShowText('你好') navbutton.setShowIcon(True) navbutton.setPaddingLeft(0) navbutton.setPaddingRight(0) navbutton.setPaddingTop(12) navbutton.setPaddingBottom(4) navbutton.setIconNormal( QPixmap(':icon/{icon}'.format(icon='navbar_home.png'))) navbutton.setIconCheck( QPixmap(':icon/{icon}'.format(icon='navbar_home.png'))) navbutton.setIconHover( QPixmap(':icon/{icon}'.format(icon='navbar_home.png'))) navbutton.setTextAlign(TextAlign_Center) navbutton.setFont(ResourceLoader().qt_font_text_xs) navbutton.setIconSize(QSize(34, 34)) navbutton.setIconPosition(IconPosition_Top) navbutton.setNormalBgColor(QColor('transparent')) navbutton.setHoverBgColor(QColor('transparent')) navbutton.setCheckBgColor(QColor('transparent')) navbutton.setNormalTextColor(QColor('#CDCDCD')) navbutton.setHoverTextColor(QColor('#FFFEFE')) navbutton.setCheckTextColor(QColor('#FFFEFE')) layout.addWidget(navbutton) spacerItem = QtWidgets.QSpacerItem(0, 100, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) layout.addSpacerItem(spacerItem)
def InitUI(self, params): mainLayout = QHBoxLayout() mainLayout.setContentsMargins(10, 0, 0, 0) mainLayout.setSpacing(0) iconLabel = QLabel() if params.type == NotificationParams.INFO or params.type == NotificationParams.HINT: iconLabel.setPixmap( qtawesome.icon('mdi.information-variant', color=ResourceLoader().qt_color_text).pixmap( QSize(self.__icon_size, self.__icon_size))) if params.type == NotificationParams.WARN: iconLabel.setPixmap( qtawesome.icon('mdi.alert-octagon', color=ResourceLoader().qt_color_warning).pixmap( QSize(self.__icon_size, self.__icon_size))) if params.type == NotificationParams.ERROR: iconLabel.setPixmap( qtawesome.icon('mdi.alert-decagram', color=ResourceLoader().qt_color_warning).pixmap( QSize(self.__icon_size, self.__icon_size))) iconLabel.setScaledContents(False) mainLayout.addWidget(iconLabel) messageLayout = QVBoxLayout() messageLayout.setContentsMargins(0, 10, 10, 12) messageLayout.setSpacing(4) mainLayout.addItem(messageLayout) titleLayout = QHBoxLayout() messageLayout.addItem(titleLayout) if self.params.type != NotificationParams.HINT and self.params.title != '': title = self.params.title labelTitle = QLabel(title) labelTitle.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum) labelTitle.setStyleSheet("font-weight: bold;font-size: 13px;") titleLayout.addWidget(labelTitle) message = self.params.message labelMessage = QLabel(message) labelMessage.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) labelMessage.setWordWrap(True) messageLayout.addWidget(labelMessage) palette = QPalette() baseColor = palette.color(QPalette.Midlight) buttonColor = baseColor buttonColor.setAlpha(0) pressedColor = baseColor pressedColor.setAlpha(255) styleSheet = str("QPushButton{border:none;}") buttonsLayout = QVBoxLayout() buttonsLayout.setContentsMargins(0, 4, 0, 4) buttonsLayout.setSpacing(0) self.closeButton = QPushButton() self.closeButton.setText("关闭") self.closeButton.setObjectName("CloseButton") self.closeButton.setProperty('type', 1) self.closeButton.setStyleSheet(styleSheet) self.closeButton.setSizePolicy( QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)) buttonsLayout.addWidget(self.closeButton) self.closeButton.clicked.connect(self.OnCloseButtonClicked) if self.params.callback: self.detailsButton = QPushButton(self.params.detailsButtonText) self.detailsButton.setProperty('type', 1) self.detailsButton.setObjectName("DetailsButton") self.detailsButton.setStyleSheet(styleSheet) self.detailsButton.setSizePolicy( QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)) buttonsLayout.addWidget(self.detailsButton) self.detailsButton.clicked.connect(self.OnDetailsButtonClicked) mainLayout.addItem(buttonsLayout) self.setLayout(mainLayout)
def __init__(self, *args, **kwargs): super(Window, self).__init__(*args, **kwargs) self.resize(500, 500) self.setStyleSheet(Style) layout = QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) # self.setLayout(layout) ''' QTableWidget ''' # table = QTableWidget(self) # table.setMinimumSize(QtCore.QSize(500, 500)) # table.setMaximumSize(QtCore.QSize(16777215, 16777215)) # table.setObjectName("tableWidget") # table.setColumnCount(2) # table.setRowCount(3) # item = QtWidgets.QTableWidgetItem() # table.setVerticalHeaderItem(0, item) # item = QtWidgets.QTableWidgetItem() # table.setVerticalHeaderItem(1, item) # item = QtWidgets.QTableWidgetItem() # table.setVerticalHeaderItem(2, item) # item = QtWidgets.QTableWidgetItem() # table.setHorizontalHeaderItem(0, item) # item = QtWidgets.QTableWidgetItem() # table.setHorizontalHeaderItem(1, item) # item = QtWidgets.QTableWidgetItem() # table.setItem(0, 0, item) # item = QtWidgets.QTableWidgetItem() # table.setItem(0, 1, item) # item = QtWidgets.QTableWidgetItem() # table.setItem(1, 0, item) # item = QtWidgets.QTableWidgetItem() # table.setItem(1, 1, item) # item = QtWidgets.QTableWidgetItem() # table.setItem(2, 0, item) # item = QtWidgets.QTableWidgetItem() # table.setItem(2, 1, item) # # table.setToolTip("This is a tool tip") # table.setStatusTip("This is a status tip") # table.setWhatsThis("This is \"what is this\"") # item = table.verticalHeaderItem(0) # item.setText("New Row") # item = table.verticalHeaderItem(1) # item.setText("New Row") # item = table.verticalHeaderItem(2) # item.setText("New Row") # item = table.horizontalHeaderItem(0) # item.setText("New Column") # item = table.horizontalHeaderItem(1) # item.setText("New Column") # __sortingEnabled = table.isSortingEnabled() # table.setSortingEnabled(False) # item = table.item(0, 0) # item.setText("1.23") # item = table.item(0, 1) # item.setText("Hello") # item = table.item(1, 0) # item.setText("1,45") # item = table.item(1, 1) # item.setText("Olá") # item = table.item(2, 0) # item.setText("12/12/2012") # item = table.item(2, 1) # item.setText("Oui") # table.setSortingEnabled(__sortingEnabled) ''' QTableView ''' # self.resize(400, 390) # self.gridLayout = QtWidgets.QGridLayout(self) # self.gridLayout.setContentsMargins(11, 11, 11, 11) # self.gridLayout.setSpacing(6) # self.gridLayout.setObjectName("gridLayout") # self.tableView = QtWidgets.QTableView(self) # self.tableView.setObjectName("tableView") # self.gridLayout.addWidget(self.tableView, 0, 0, 1, 1) # # model = TableModel(rowCount=1000, pageSize=20) # self.tableView.setModel(model) # self.tableView.horizontalHeader().setStretchLastSection(True) ''' QTableView With Pagination ''' self.setFixedSize(600, 450) self.gridLayout = QtWidgets.QGridLayout(self) self.gridLayout.setContentsMargins(11, 11, 11, 11) self.gridLayout.setSpacing(6) self.gridLayout.setObjectName("gridLayout") # 头部 label_icon_search = QLabel() label_icon_search.setPixmap( qtawesome.icon('fa5s.search', color=ResourceLoader().qt_color_sub_text).pixmap( QSize(18, 18))) label_icon_search.setFixedSize(20, 20) self.input_search = BaseLineEdit(leftWidget=label_icon_search) self.input_search.setFixedHeight(32) self.input_search.setLeftRightLayoutMargin(10, 10) self.input_search.setPlaceholderText("输入查询条件") self.gridLayout.addWidget(self.input_search, 0, 0, 1, 1) btn_search = QPushButton() btn_search.setProperty("type", 1) btn_search.setText("查询") btn_search.clicked.connect(self.search) self.gridLayout.addWidget(btn_search, 0, 1, 1, 1) btn_reset = QPushButton() btn_reset.setProperty("type", 1) btn_reset.setText("重置") btn_reset.clicked.connect(self.reset) self.gridLayout.addWidget(btn_reset, 0, 2, 1, 1) separator = Separator(self) separator.setFixedHeight(2) self.gridLayout.addWidget(separator, 1, 0, 1, 10) # 表格 self.tableView = QtWidgets.QTableView(self) self.tableView.setObjectName("tableView") self.gridLayout.addWidget(self.tableView, 2, 0, 1, 10) separator = Separator(self) separator.setFixedHeight(2) self.gridLayout.addWidget(separator, 3, 0, 1, 10) # 分页栏 self.paginationBar1 = CPaginationBar(self, totalPages=20) self.paginationBar1.setInfos('共 400 条') self.paginationBar1.setJumpWidget(True) self.paginationBar1.pageChanged.connect( lambda page: self.model.fetchData(page=page - 1)) self.gridLayout.addWidget(self.paginationBar1, 4, 0, 1, 10) self.model = TableModel(self, api=self.api, pagination=self.paginationBar1) # self.model.setHeaderData(0, Qt.Horizontal, "姓名") # self.model.setHeaderData(1, Qt.Horizontal, "姓名") # self.model.setHeaderData(2, Qt.Horizontal, "姓名") # self.model.setHeaderData(0, Qt.Vertical, "姓名") # self.model.setHeaderData(1, Qt.Vertical, "姓名") # self.model.setHeaderData(2, Qt.Vertical, "姓名") def mock(): # self.model.fetchData(0) self.model.fetchData() QTimer.singleShot(2000, mock) self.model.m_headData = ['hello', 'Then'] self.tableView.setModel(self.model) self.tableView.horizontalHeader().setStretchLastSection(True)
class BaseView(QWidget): ''' 静态资源管理器 ''' resource: ResourceLoader = ResourceLoader() ''' 路由管理器 ''' router: RouteManager = RouteManager() ''' 全局数据块 ''' global_bloc: Bloc_App = Bloc_App() ''' 配置对象 ''' config = Config() ''' 主题对象 ''' theme = Theme() ''' 图标字体 ''' fontawesome = FontAwesome() def set_style(self): ''' 设置样式 https://stackoverflow.com/questions/31178695/qt-stylesheet-not-working ''' self.setAttribute(QtCore.Qt.WA_StyledBackground) if hasattr(self, 'style_name'): with open(Config().qss_path + '/' + self.style_name + '.qss', 'r', encoding='utf-8') as f: self.setStyleSheet(f.read()) def procedure(self): ''' 初始化流程,set_ui > place > configure > set_signal ''' self.set_style() if hasattr(self, 'set_ui'): self.set_ui() if hasattr(self, 'place'): self.place() if hasattr(self, 'configure'): self.configure() if hasattr(self, 'set_bloc'): self.set_bloc() if hasattr(self, 'set_signal'): self.set_signal() def show_vloading(self): if not hasattr(self, 'inner_loader'): self.inner_loader = Loading(self, modal=False) self.inner_loader.show() def hide_vloading(self): if hasattr(self, 'inner_loader'): self.inner_loader.on_outer_close.emit()
def paint(self, painter: QtGui.QPainter, option: 'QStyleOptionViewItem', index: QtCore.QModelIndex) -> None: if not index.isValid(): return if option.state & QStyle.State_Selected: pass if option.state & QStyle.State_MouseOver: pass item = index.model().data(index, Qt.UserRole) if isinstance(item, QVariant): return painter.setRenderHint(QPainter.Antialiasing, True) painter.setRenderHints(QPainter.SmoothPixmapTransform) value = item['value'] type = item['type'] x = option.rect.x() y = option.rect.y() w = option.rect.width() h = option.rect.height() if type == 'device_activity': painter.save() # 图标 icon = QImage(ResourceLoader().icon_path(value['icon'])) rect_icon = QRectF(x + 20, y + 13, 44, 44) painter.drawImage(rect_icon, icon) # 设备标签 painter.setFont(ResourceLoader().qt_font_text_xs) rect = calculate_text_rect('设备', painter=painter, x=x + 70, y=y + 15) painter.drawText(rect, Qt.TextSingleLine, '设备') # 设备编号 painter.setPen(ResourceLoader().qt_color_label_link) painter.setFont(ResourceLoader().qt_font_text_xs) rect = calculate_text_rect(value['device'], painter=painter, x=x + 110, y=y + 15) painter.drawText(rect, Qt.TextSingleLine, value['device']) # 活动内容 painter.setPen(ResourceLoader().qt_color_sub_text) painter.setFont(ResourceLoader().qt_font_text_xss) content = value['content'] + ',' + toDateStr() rect = calculate_text_rect(content, painter=painter, x=x + 70, y=y + 40) painter.drawText(rect, Qt.TextSingleLine, content) # 绘制边框 path = QPainterPath() path.addRoundedRect(QRectF(x + 4, y + 4, w - 8, h - 8), 4, 4) painter.strokePath(path, QPen(ResourceLoader().qt_color_background, 1)) painter.restore() elif type == 'load_more': # 绘制加载图标 # painter.save() # painter.translate(x+16, y+16) # self.loading_rotate += 5 # painter.rotate(self.loading_rotate%360) # icon = qtawesome.icon('mdi.loading', color=ResourceLoader().qt_color_sub_text) # icon_pixmap = icon.pixmap(QSize(32, 32)) # painter.drawPixmap(QRect(-16, -16, 32, 32), icon_pixmap) # painter.restore() # 绘制加载信息 painter.save() painter.setFont(ResourceLoader().qt_font_text_xs) painter.setPen(ResourceLoader().qt_color_sub_text) _rect = calculate_text_rect('~~~ 正在努力加载 ~~~', painter=painter) rect = calculate_middle_rect(option.rect, width=_rect.width(), height=_rect.height()) painter.drawText(rect, Qt.TextSingleLine, '~~~ 正在努力加载 ~~~') painter.restore() elif type == 'no_more': painter.save() painter.setFont(ResourceLoader().qt_font_text_xs) painter.setPen(ResourceLoader().qt_color_sub_text) _rect = calculate_text_rect('--- 我是有底线的 ---', painter=painter) rect = calculate_middle_rect(option.rect, width=_rect.width(), height=_rect.height()) painter.drawText(rect, Qt.TextSingleLine, '--- 我是有底线的 ---') painter.restore() else: self.initStyleOption(option, index) QStyledItemDelegate.paint(self, painter, option, index)