Esempio n. 1
0
    def set_layout(self):
        layout = QVBoxLayout()

        up_widget = QWidget()
        up_layout = QHBoxLayout(up_widget)
        up_left_widget = QWidget()
        up_left_layout = QVBoxLayout(up_left_widget)
        up_left_layout.addWidget(self.inputBtn)
        up_left_layout.addWidget(self.inputText)
        up_left_layout.addStretch(1)
        up_left_layout.addWidget(self.outputBtn)
        up_left_layout.addWidget(self.outputText)
        up_left_layout.addStretch(1)
        up_left_layout.addWidget(self.executeBtn)
        up_left_layout.addStretch(2)
        upRightWidget = QWidget()
        upRightlayout = QVBoxLayout(upRightWidget)
        upRightlayout.addWidget(self.logInfo)
        up_layout.addWidget(up_left_widget)
        up_layout.addWidget(upRightWidget)

        down_widet = QWidget()
        down_layout = QVBoxLayout(down_widet)
        down_layout.addWidget(QLabel("运行结果"))
        down_layout.addWidget(self.resTable)

        layout.addWidget(up_widget)
        layout.setStretchFactor(up_widget, 3)
        layout.addWidget(down_widet)
        layout.setStretchFactor(down_widet, 7)
        self.setLayout(layout)
Esempio n. 2
0
class SynchronizationInterface(QWidget):
    def __init__(self, parent, shared_data):
        super(SynchronizationInterface, self).__init__(parent)
        self.__shared_data = shared_data

        # Create the widgets
        self.__video_widget = VideoWidget(self, self.__shared_data)
        self.__data_widget = DataWidget(self, self.__shared_data)
        self.__sidebar_widget = SideBarWidget(self, self.__shared_data)

        # Create the layouts
        self.__left_layout = QVBoxLayout()
        self.__left_layout.addWidget(self.__video_widget)
        self.__left_layout.addWidget(self.__data_widget)
        self.__left_layout.setStretchFactor(self.__video_widget, 2)
        self.__left_layout.setStretchFactor(self.__data_widget, 1)

        self.__main_layout = QHBoxLayout()
        self.__main_layout.addLayout(self.__left_layout)
        self.__main_layout.addWidget(self.__sidebar_widget)
        self.__main_layout.setStretchFactor(self.__left_layout, 3)
        self.__main_layout.setStretchFactor(self.__sidebar_widget, 1)

        # Set the layout
        self.setLayout(self.__main_layout)
Esempio n. 3
0
class GraphView3D(QWidget):
    def __init__(self, parent=None):
        super(QWidget, self).__init__(parent)
        self.dpi = 100
        self.fig = Figure((5.0, 3.0),
                          dpi=self.dpi,
                          facecolor=(1, 1, 1),
                          edgecolor=(0, 0, 0))
        self.axes = self.fig.add_subplot(111, projection='3d')
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.canvas)
        self.layout.addWidget(self.toolbar)
        self.layout.setStretchFactor(self.canvas, 1)
        self.setLayout(self.layout)
        self.font = QtGui.QFont()
        self.font.setPointSize(1)
        self.canvas.show()
        self.axes.mouse_init()

    def update_graph(self, data, title, axis_labels):
        self.axes.cla()
        self.axes.mouse_init()
        colors = cycle(
            ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"])
        for item in range(len(data)):
            self.axes.plot3D(data[item][0],
                             data[item][1],
                             data[item][2],
                             color=next(colors))  #, label=labels[item])
        # self.axes.legend(loc="best")
        self.axes.set_title(title)
        self.axes.set_xlabel(axis_labels[0])
        self.axes.set_ylabel(axis_labels[1])
        self.axes.set_zlabel(axis_labels[2])
        self.axes.view_init(-90, 90)
        self.canvas.draw()

    def update_scatter(self, data, title, labels, axis_labels):
        self.axes.cla()
        self.axes.clear()
        self.axes.mouse_init()
        colors = cycle(
            ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"])
        for item in range(len(data)):
            self.axes.scatter(data[item][0],
                              data[item][1],
                              data[item][2],
                              color=next(colors),
                              label=labels[item],
                              s=1)
        self.axes.legend(loc="best")
        self.axes.set_title(title)
        self.axes.set_xlabel(axis_labels[0])
        self.axes.set_ylabel(axis_labels[1])
        self.axes.set_zlabel(axis_labels[2])
        self.axes.view_init(-90, 90)
        self.canvas.draw()
Esempio n. 4
0
class GraphView2D(QWidget):
    def __init__(self, parent=None):
        super(QWidget, self).__init__(parent)
        self.dpi = 100
        self.fig = Figure((5.0, 3.0),
                          dpi=self.dpi,
                          facecolor=(1, 1, 1),
                          edgecolor=(0, 0, 0))
        self.axes = self.fig.add_subplot(111)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.canvas)
        self.layout.addWidget(self.toolbar)
        self.layout.setStretchFactor(self.canvas, 1)
        self.setLayout(self.layout)
        self.font = QtGui.QFont()
        self.font.setPointSize(1)
        self.canvas.show()

    def update_graph(self, data, title, axis_labels):
        self.axes.clear()
        colors = cycle(
            ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"])
        for item in range(len(data)):
            self.axes.plot(data[item], color=next(colors))
        # self.axes.legend(frameon=True)
        # self.axes.legend(loc="best")
        self.axes.set_title(title)
        self.axes.set_xlabel(axis_labels[0])
        self.axes.set_ylabel(axis_labels[1])
        self.axes.grid(linestyle='--')
        self.canvas.draw()
Esempio n. 5
0
    def init_ui(self, colc=5):
        self.colc = colc
        self.setGeometry(200, 100, 900, 600)
        self.setWindowTitle('RF_cas_cal tool')

        compound_widget = QWidget()
        self.table1 = QTableWidget()
        self.table2 = QTableWidget()
        # self.table2.resize(50,50)  #设置表格尺寸
        # ===1:创建初始表格
        # self.colc = 5
        self.table1.setColumnCount(self.colc)
        self.table1.setRowCount(9)
        # self.table1.setStyleSheet()
        self.table2.setColumnCount(6)
        self.table2.setRowCount(4)
        # self.setShowGrid(False) #是否需要显示网格

        # hbox = QHBoxLayout()
        # hbox.addWidget(self.table2)

        vbox = QVBoxLayout()
        vbox.addWidget(self.table1)
        # vbox.addStretch(1)
        vbox.addWidget(self.table2)
        vbox.setStretchFactor(self.table1, 2)
        vbox.setStretchFactor(self.table2, 1)
        compound_widget.setLayout(vbox)
        self.setCentralWidget(compound_widget)

        self.settableHeader()
        self.settableHeaderVisible()

        self.inputrow_class(self.colc)
        self.inputrow_model(self.colc)
        self.inputrow_frq(self.colc)
        self.inputrow4_5(self.colc)
        self.inputrow7_8(self.colc)
        self.inputrow9()
        self.inputrow10(self.colc)
        self.editsheet_label()
        self.editsheet_value_class()
        self.editsheet_value_model()
        self.editsheet_value_frq()
        self.editsheet_value_gain_nf()
        self.buttun_edit()
        # self.settableHeaderFontColor()
        # self.setCellFontColor()
        # self.setCellAlign()
        # self.setCellFontSize()
        # self.setCellFontColor()
        # self.setCellSpan()

        # layout = QHBoxLayout()
        # layout.addWidget(MyTable)
        # self.setLayout(layout)

        self.table1.itemChanged.connect(self.table1_item_textchanged)
        self.table2.itemChanged.connect(self.table2_item_textchanged)
Esempio n. 6
0
    def initUI(self):
        painter = QPainter(self)
        painter.setPen(QPen(Qt.black, 5, Qt.SolidLine))
        #painter.setBrush(QBrush(Qt.red, Qt.SolidPattern))
        painter.setBrush(QBrush(Qt.green, Qt.DiagCrossPattern))
        painter.drawRect(100, 15, 400 ,200)
        
        
        layout = QVBoxLayout()


        vbox = QHBoxLayout()
        vbox.setSpacing(20)

        menu = QVBoxLayout()
        menu.setAlignment(QtCore.Qt.AlignCenter)
        menu.setSpacing(40)

        b1 = QPushButton("save")
        b1.setStyleSheet("QPushButton { background-color: #2E3D50;color:#ffffff; border: none; font-weight: regular; font-size: 15pt;font-family: Calibri;}")
        menu.addWidget(b1)
        b2 = QPushButton("reset")
        b2.setStyleSheet("QPushButton { background-color: #2E3D50;color:#ffffff; border: none; font-weight: regular; font-size: 15pt;font-family: Calibri;}")
        menu.addWidget(b2)
        b3 = QPushButton("connect")
        b3.setStyleSheet("QPushButton { background-color: #2E3D50;color:#ffffff; border: none; font-weight: regular; font-size: 15pt;font-family: Calibri;}")
        menu.addWidget(b3)
        b4 = QPushButton("option")
        b4.setStyleSheet("QPushButton { background-color: #2E3D50;color:#ffffff; border: none; font-weight: regular; font-size: 15pt;font-family: Calibri;}")
        menu.addWidget(b4)

        
        vbox.addLayout(menu)
        vbox.setStretchFactor(menu, 1)
        
        vbox.addWidget(self.canvas)
        vbox.setStretchFactor(self.canvas, 4)
        self.setLayout(vbox)

        status = QLineEdit()
        layout.addWidget(status)
        layout.addLayout(vbox)
        
        layout.setStretchFactor(vbox, 1)
        layout.setStretchFactor(status, 4)
        self.setLayout(layout)

        #self.setGeometry(0,0,800,400)
         
        # 1~1 중 1번째(1,1,1)  서브 챠트 생성
        self.ax = self.fig.add_subplot(111, projection='3d')         
        # 2D line
        self.plot = [self.ax.plot_surface(self.x, self.y, self.zarray, color='0.75', rstride=1, cstride=1)]
        self.ax.set_zlim(0,1.1)
        ani = animation.FuncAnimation(self.fig, self.update_plot, interval=1000/self.fps)

        self.canvas.draw()
Esempio n. 7
0
class WxClientsCtrlPanel(QFrame):
    def __init__(self, parent=None, wxclients={}, **callbacks):
        super().__init__(parent)
        self.wxclients = wxclients
        self.callbacks = callbacks
        self.layout = QVBoxLayout(self)
        self.setLayout(self.layout)
        self.clientCtrlItems = []
        for wxclient in self.wxclients:
            item = WxClientCtrlItem(self, wxclient,
                                    self.wxclients[wxclient]["url"])
            self.clientCtrlItems.append(item)
        self.logArea = QTextEdit(self)
        self.logArea.setReadOnly(True)
        self.btnRunAll = QPushButton(self)
        self.btnClearLog = QPushButton(self)
        self.btnClearLog.setText("清空日志")
        self.btnClearLog.clicked.connect(self.onClickedClearLog)
        self.btnRunAll.setText("一键运行")
        self.btnRunAll.clicked.connect(self.onClickedRunAll)
        self.putComponents()
        self.logArea.setHtml(notice)

    def putComponents(self):
        for item in self.clientCtrlItems:
            self.layout.addWidget(item)
        self.layout.addWidget(self.btnRunAll)
        self.layout.addWidget(self.btnClearLog)
        self.layout.addWidget(self.logArea)
        self.layout.setStretchFactor(self.logArea, 10)

    def log(self, content):
        self.logArea.append(content)

    def onClickedRunAll(self):
        urls = []
        for item in self.clientCtrlItems:
            if not item.isSelected(): continue
            url = item.getUrl()
            if url.strip() != "":
                urls.append(url)
            else:
                QMessageBox.information(None, "错误",
                                        f"{item.lblTitle.text()} 地址为空",
                                        QMessageBox.Yes)
                return
        if "runAllClients" in self.callbacks:
            self.callbacks["runAllClients"](urls)

    def onClickedClearLog(self):
        self.logArea.clear()
Esempio n. 8
0
    def setupUi(self, Dialog):
        Dialog.setObjectName("ModelTrainDescriptionDialog")
        Dialog.resize(700, 600)
        Dialog.setStyleSheet(GetQssFile.readQss('../resource/qss/modelTrainDescriptionDialog.qss'))

        frame = QFrame(Dialog)
        frame.setGeometry(Dialog.geometry())

        main_layout = QVBoxLayout(Dialog, spacing=0)
        main_layout.setContentsMargins(0, 0, 0, 0)
        description_widget = self.get_description_widget()
        main_layout.addWidget(description_widget)
        main_layout.setStretchFactor(description_widget, 1)

        ModelTrainDescriptionDialog.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)
Esempio n. 9
0
 def init_framework(self, pubconig_height):
     self.pubConfigWidget = QtWidgets.QWidget()
     self.pubConfigWidget.setFixedHeight(pubconig_height)
     self.pubConfigWidget.setContentsMargins(0, 0, 0, 0)
     pubConfigGridLayout = QtWidgets.QGridLayout()
     pubConfigGridLayout.setContentsMargins(0, 0, 0, 0)
     pubConfigGridLayout = QtWidgets.QGridLayout()
     pubConfigGridLayout.setContentsMargins(0, 0, 0, 0)
     pubConfigGridLayout.setVerticalSpacing(13)
     self.pubConfigWidget.setLayout(pubConfigGridLayout)
     self.actionBox = QtWidgets.QToolBox()
     self.actionBox.layout().setContentsMargins(0, 0, 0, 0)
     qvblayout = QVBoxLayout()
     qvblayout.addWidget(self.pubConfigWidget)
     qvblayout.addWidget(self.actionBox)
     qvblayout.setStretchFactor(self.actionBox, 100)
     self._action_pannel.setLayout(qvblayout)
     self._action_pannel.layout().setContentsMargins(0, 0, 0, 0)
Esempio n. 10
0
    def initfilesview(self):
        # Create widget to host the scanner and add it to the splitter
        scannerw = QWidget(self)
        vl = QVBoxLayout(scannerw)

        self.descriptionw = QTextEdit(scannerw)
        btnsave = QPushButton("Save description")
        self.listw = QListWidget(scannerw)

        self.listw.setItemDelegate(FileListDelegate())

        btnsave.clicked.connect(self.savedescription)

        vl.addWidget(self.descriptionw)
        vl.addWidget(btnsave)
        vl.addWidget(self.listw)

        vl.setStretchFactor(self.listw, 10)
Esempio n. 11
0
    def _finalize_init(self,
                       session,
                       models,
                       attr_names,
                       scores_fetched=False):
        self.models = models
        self.attr_names = attr_names
        from chimerax.core.models import REMOVE_MODELS
        self.handlers = [
            session.triggers.add_handler(REMOVE_MODELS,
                                         self._models_removed_cb)
        ]

        from chimerax.ui import MainToolWindow
        self.tool_window = MainToolWindow(self,
                                          close_destroys=False,
                                          statusbar=False)
        self.tool_window.fill_context_menu = self.fill_context_menu
        parent = self.tool_window.ui_area

        from PyQt5.QtWidgets import QTableWidget, QVBoxLayout, QAbstractItemView, QWidget, QPushButton
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        parent.setLayout(layout)
        self.table = QTableWidget()
        self.table.setSortingEnabled(True)
        self.table.keyPressEvent = session.ui.forward_keystroke
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.table.itemSelectionChanged.connect(self._table_selection_cb)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        layout.addWidget(self.table)
        layout.setStretchFactor(self.table, 1)
        self._fill_table()
        self.tool_window.manage('side')
        self.scores_fetched = scores_fetched
        for m in models:
            self.handlers.append(
                m.triggers.add_handler("changes", self._changes_cb))
Esempio n. 12
0
class GraphViewHeatMap(QWidget):
    def __init__(self, parent=None):
        super(QWidget, self).__init__(parent)

        self.dpi = 100
        self.fig = Figure((5.0, 3.0),
                          dpi=self.dpi,
                          facecolor=(1, 1, 1),
                          edgecolor=(0, 0, 0))
        self.axes = self.fig.add_subplot(111, projection='3d')
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.canvas)
        self.layout.addWidget(self.toolbar)
        self.layout.setStretchFactor(self.canvas, 1)
        self.setLayout(self.layout)
        self.font = QtGui.QFont()
        self.font.setPointSize(1)
        self.canvas.show()
        self.axes.mouse_init()

    def update_graph(self, map_x, map_y, data, title, axis_labels):
        self.fig.clf()
        self.axes = self.fig.add_subplot(111, projection='3d')
        surf = self.axes.plot_surface(map_x,
                                      map_y,
                                      data,
                                      cmap=cm.YlGnBu,
                                      linewidth=0,
                                      antialiased=False)
        self.axes.set_title(title)
        self.axes.set_xlabel(axis_labels[0])
        self.axes.set_ylabel(axis_labels[1])
        self.axes.set_zlabel(axis_labels[2])
        self.fig.colorbar(surf, shrink=0.5, aspect=5)
        self.axes.mouse_init()
        self.canvas.draw()
Esempio n. 13
0
    def initUI(self):

        self.showtable = None
        self.radioButtons = []
        self.rownum = 0
        self.colnum = 2

        self.cenerLayout = QVBoxLayout()
        self.createTable(getVoteActivities(self.usr))

        self.showButton = QPushButton('查看结果')
        self.showButton.setFont(QFont('微软雅黑'))
        self.showButton.setIcon(QIcon('./image/search.png'))
        self.showButton.clicked.connect(self.onShow)
        
        self.delButton = QPushButton('删除活动')
        self.delButton.setFont(QFont('微软雅黑'))
        self.delButton.setIcon(QIcon('./image/delete.jpg'))
        self.delButton.clicked.connect(self.onDel)

        downhbox = QHBoxLayout()
        downhbox.addStretch(1)
        downhbox.addWidget(self.showButton)
        downhbox.addWidget(self.delButton)
        downhbox.addStretch(1)

        totalLayout = QVBoxLayout()
        totalLayout.addLayout(self.cenerLayout)
        totalLayout.addLayout(downhbox)
        totalLayout.setStretchFactor(self.cenerLayout, 3)
        totalLayout.setStretchFactor(downhbox, 1)

        self.setLayout(totalLayout)

        center(self)
        self.resize(600, 270)
        self.setWindowTitle('投票查看')
        self.setWindowIcon(QIcon('./image/view.png'))
Esempio n. 14
0
class ImageView(QWidget):
    """
    Usage:
        app = QApplication(sys.argv)

        imageshow = ImageView()

        imageshow.show_image([a_crater, a_guess_mask])

        imageshow.show()

        sys.exit(app.exec_())
    """
    def __init__(self, parent=None):
        super(QWidget, self).__init__(parent)
        self.dpi = 100
        self.fig = Figure((5.0, 3.0), dpi=self.dpi, facecolor=(1, 1, 1), edgecolor=(0, 0, 0))
        self.axes = []
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.canvas)
        self.layout.addWidget(self.toolbar)
        self.layout.setStretchFactor(self.canvas, 1)
        self.setLayout(self.layout)
        self.font = QtGui.QFont()
        self.font.setPointSize(1)
        self.canvas.show()

    def set_image(self, images, target):
        for i in range(len(images)):
            self.axes.append(self.fig.add_subplot(1, len(images), i+1))
            self.axes[i].imshow(images[i])
            self.axes[i].grid()
        self.fig.suptitle("AS16-M-0" + str(target['filename'].numpy()) + ".jpg")
        self.canvas.draw()
Esempio n. 15
0
    def initUI(self):
        self.create_cmd_input()
        self.create_test_status_show()
        self.create_info_show()
        self.create_po_progressbar_show()

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.gridGroupBox)
        mainLayout.addWidget(self.formGroupBox_test_status)
        mainLayout.addWidget(self.QGroupBox_info_show)
        mainLayout.addWidget(self.QGridLayout_po_progress)

        mainLayout.setStretchFactor(self.gridGroupBox, 25)
        mainLayout.setStretchFactor(self.formGroupBox_test_status, 10)
        mainLayout.setStretchFactor(self.QGroupBox_info_show, 65)
        mainLayout.setStretchFactor(self.QGridLayout_po_progress, 5)
        self.setLayout(mainLayout)
Esempio n. 16
0
    def init_ui(self):
        self.create_cmd_input()
        self.create_info_show()
        self.create_po_progressbar_show()

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.gridGroupBox)
        mainLayout.addWidget(self.QGroupBox_info_show)
        mainLayout.addWidget(self.QGridLayout_po_progress)

        mainLayout.setStretchFactor(self.gridGroupBox, 30)
        mainLayout.setStretchFactor(self.QGroupBox_info_show, 65)
        mainLayout.setStretchFactor(self.QGridLayout_po_progress, 5)
        self.setLayout(mainLayout)
Esempio n. 17
0
    def __init__(self, parent=None):
        super().__init__(parent)
        layout = QVBoxLayout()
        self.setLayout(layout)
        self.profile = QWebEngineProfile()
        self.store = self.profile.cookieStore()
        self.brower = QWebEngineView()
        self.profile.cookieStore().cookieAdded.connect(self.onCookieAdd)
        page = QWebEnginePage(self.profile, self.brower)
        page.setUrl(QUrl("https://passport.csdn.net/login?code=public"))
        self.brower.setPage(page)
        self.title = QLabel()
        self.edit = QTextEdit()
        #self.edit=QCodeEditor()
        layout.addWidget(self.title)
        layout.addWidget(self.brower)
        layout.addWidget(self.edit)
        layout.setStretchFactor(self.title, 1)
        layout.setStretchFactor(self.brower, 10)
        layout.setStretchFactor(self.edit, 10)
        self.title.setHidden(True)
        self.edit.setHidden(True)

        #当edit的内容改动的时候,broswer的内容要同步进行刷新
        self.edit.textChanged.connect(self.refreshBrowser)

        #快捷查找
        self.contentSearch = QLineEdit(returnPressed=lambda: self.brower.
                                       findText(self.contentSearch.text()))
        self.contentSearch.setWindowTitle("搜索")
        self.contentSearch.hide()
        self.showSearch = QShortcut(
            "Ctrl+F",
            self,
            activated=lambda:
            (self.contentSearch.show(), self.contentSearch.setFocus()))
Esempio n. 18
0
    def __init__(self, config_dir):
        super(RSSReaderWidget, self).__init__()

        self.feed_file_path = os.path.join(config_dir, "rss-reader", "feeds.json")

        self.feed_area = QWidget()
        self.feed_list = QListWidget()
        self.feed_list.setStyleSheet( """QListView {background: #4D5250; show-decoration-selected: 1; selection-background-color: #464646;}""")
        panel_layout = QVBoxLayout()
        panel_layout.setSpacing(0)
        panel_layout.setContentsMargins(0, 0, 0, 0)
        panel_layout.addWidget(self.feed_list)
        self.feed_area.setLayout(panel_layout)

        self.article_area = QWidget()
        self.article_list = QListWidget()
        self.article_list.setStyleSheet( """QListView {background: #FFF; show-decoration-selected: 1; selection-background-color: #EEE;}""")
        self.article_list.verticalScrollBar().setStyleSheet("QScrollBar {width:0px;}");
        article_layout = QVBoxLayout()
        article_layout.setSpacing(0)
        article_layout.setContentsMargins(0, 0, 0, 0)

        self.browser = BrowserView(config_dir)

        article_layout.addWidget(self.article_list)
        article_layout.addWidget(self.browser)

        article_layout.setStretchFactor(self.article_list, 1)
        article_layout.setStretchFactor(self.browser, 3)

        self.article_area.setLayout(article_layout)

        self.welcome_page = QWidget()
        self.welcome_page_box = QVBoxLayout()
        self.welcome_page_box.setSpacing(10)
        self.welcome_page_box.setContentsMargins(0, 0, 0, 0)

        welcome_title_label = QLabel("Welcome to EAF RSS Reader!")
        welcome_title_label.setFont(QFont('Arial', 24))
        welcome_title_label.setStyleSheet("QLabel {color: #333; font-weight: bold; margin: 20px;}")
        welcome_title_label.setAlignment(Qt.AlignHCenter)

        add_subscription_label = QLabel("Press 'a' to subscribe to a feed!")
        add_subscription_label.setFont(QFont('Arial', 20))
        add_subscription_label.setStyleSheet("QLabel {color: #grey;}")
        add_subscription_label.setAlignment(Qt.AlignHCenter)

        self.welcome_page_box.addStretch(1)
        self.welcome_page_box.addWidget(welcome_title_label)
        self.welcome_page_box.addWidget(add_subscription_label)
        self.welcome_page_box.addStretch(1)

        self.welcome_page.setLayout(self.welcome_page_box)

        self.right_area = QStackedWidget()
        self.right_area.addWidget(self.welcome_page)
        self.right_area.addWidget(self.article_area)

        if self.has_feed():
            self.right_area.setCurrentIndex(1)
        else:
            self.right_area.setCurrentIndex(0)

        hbox = QHBoxLayout()
        hbox.setSpacing(0)
        hbox.setContentsMargins(0, 0, 0, 0)

        hbox.addWidget(self.feed_area)
        hbox.addWidget(self.right_area)

        hbox.setStretchFactor(self.feed_area, 1)
        hbox.setStretchFactor(self.right_area, 3)

        self.setLayout(hbox)

        self.feed_list.itemActivated.connect(self.handle_feed)
        self.article_list.itemActivated.connect(self.handle_article)

        self.feed_object_dict = {}

        self.init_select_line = False

        self.fetch_feeds()
Esempio n. 19
0
class DebugViewer(QWidget):
    """
    Class implementing a widget conatining various debug related views.
    
    The individual tabs contain the interpreter shell (optional),
    the filesystem browser (optional), the two variables viewers
    (global and local), a breakpoint viewer, a watch expression viewer and
    the exception logger. Additionally a list of all threads is shown.
    
    @signal sourceFile(string, int) emitted to open a source file at a line
    """
    sourceFile = pyqtSignal(str, int)
    
    def __init__(self, debugServer, docked, vm, parent=None,
                 embeddedShell=True, embeddedBrowser=True):
        """
        Constructor
        
        @param debugServer reference to the debug server object
        @param docked flag indicating a dock window
        @param vm reference to the viewmanager object
        @param parent parent widget (QWidget)
        @param embeddedShell flag indicating whether the shell should be
            included. This flag is set to False by those layouts, that have
            the interpreter shell in a separate window.
        @param embeddedBrowser flag indicating whether the file browser should
            be included. This flag is set to False by those layouts, that
            have the file browser in a separate window or embedded
            in the project browser instead.
        """
        super(DebugViewer, self).__init__(parent)
        
        self.debugServer = debugServer
        self.debugUI = None
        
        self.setWindowIcon(UI.PixmapCache.getIcon("eric.png"))
        
        self.__mainLayout = QVBoxLayout()
        self.__mainLayout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.__mainLayout)
        
        self.__tabWidget = E5TabWidget()
        self.__mainLayout.addWidget(self.__tabWidget)
        
        self.embeddedShell = embeddedShell
        if embeddedShell:
            from QScintilla.Shell import ShellAssembly
            # add the interpreter shell
            self.shellAssembly = ShellAssembly(debugServer, vm, False)
            self.shell = self.shellAssembly.shell()
            index = self.__tabWidget.addTab(
                self.shellAssembly,
                UI.PixmapCache.getIcon("shell.png"), '')
            self.__tabWidget.setTabToolTip(index, self.shell.windowTitle())
        
        self.embeddedBrowser = embeddedBrowser
        if embeddedBrowser:
            from UI.Browser import Browser
            # add the browser
            self.browser = Browser()
            index = self.__tabWidget.addTab(
                self.browser,
                UI.PixmapCache.getIcon("browser.png"), '')
            self.__tabWidget.setTabToolTip(index, self.browser.windowTitle())
        
        from .VariablesViewer import VariablesViewer
        # add the global variables viewer
        self.glvWidget = QWidget()
        self.glvWidgetVLayout = QVBoxLayout(self.glvWidget)
        self.glvWidgetVLayout.setContentsMargins(0, 0, 0, 0)
        self.glvWidgetVLayout.setSpacing(3)
        self.glvWidget.setLayout(self.glvWidgetVLayout)
        
        self.globalsViewer = VariablesViewer(self.glvWidget, True)
        self.glvWidgetVLayout.addWidget(self.globalsViewer)
        
        self.glvWidgetHLayout = QHBoxLayout()
        self.glvWidgetHLayout.setContentsMargins(3, 3, 3, 3)
        
        self.globalsFilterEdit = QLineEdit(self.glvWidget)
        self.globalsFilterEdit.setSizePolicy(
            QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.glvWidgetHLayout.addWidget(self.globalsFilterEdit)
        self.globalsFilterEdit.setToolTip(
            self.tr("Enter regular expression patterns separated by ';'"
                    " to define variable filters. "))
        self.globalsFilterEdit.setWhatsThis(
            self.tr("Enter regular expression patterns separated by ';'"
                    " to define variable filters. All variables and"
                    " class attributes matched by one of the expressions"
                    " are not shown in the list above."))
        
        self.setGlobalsFilterButton = QPushButton(
            self.tr('Set'), self.glvWidget)
        self.glvWidgetHLayout.addWidget(self.setGlobalsFilterButton)
        self.glvWidgetVLayout.addLayout(self.glvWidgetHLayout)
        
        index = self.__tabWidget.addTab(
            self.glvWidget,
            UI.PixmapCache.getIcon("globalVariables.png"), '')
        self.__tabWidget.setTabToolTip(index, self.globalsViewer.windowTitle())
        
        self.setGlobalsFilterButton.clicked.connect(
            self.__setGlobalsFilter)
        self.globalsFilterEdit.returnPressed.connect(self.__setGlobalsFilter)
        
        # add the local variables viewer
        self.lvWidget = QWidget()
        self.lvWidgetVLayout = QVBoxLayout(self.lvWidget)
        self.lvWidgetVLayout.setContentsMargins(0, 0, 0, 0)
        self.lvWidgetVLayout.setSpacing(3)
        self.lvWidget.setLayout(self.lvWidgetVLayout)
        
        self.lvWidgetHLayout1 = QHBoxLayout()
        self.lvWidgetHLayout1.setContentsMargins(3, 3, 3, 3)
        
        self.stackComboBox = QComboBox(self.lvWidget)
        self.stackComboBox.setSizePolicy(
            QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.lvWidgetHLayout1.addWidget(self.stackComboBox)

        self.sourceButton = QPushButton(self.tr('Source'), self.lvWidget)
        self.lvWidgetHLayout1.addWidget(self.sourceButton)
        self.sourceButton.setEnabled(False)
        self.lvWidgetVLayout.addLayout(self.lvWidgetHLayout1)

        self.localsViewer = VariablesViewer(self.lvWidget, False)
        self.lvWidgetVLayout.addWidget(self.localsViewer)
        
        self.lvWidgetHLayout2 = QHBoxLayout()
        self.lvWidgetHLayout2.setContentsMargins(3, 3, 3, 3)
        
        self.localsFilterEdit = QLineEdit(self.lvWidget)
        self.localsFilterEdit.setSizePolicy(
            QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.lvWidgetHLayout2.addWidget(self.localsFilterEdit)
        self.localsFilterEdit.setToolTip(
            self.tr(
                "Enter regular expression patterns separated by ';' to define "
                "variable filters. "))
        self.localsFilterEdit.setWhatsThis(
            self.tr(
                "Enter regular expression patterns separated by ';' to define "
                "variable filters. All variables and class attributes matched"
                " by one of the expressions are not shown in the list above."))
        
        self.setLocalsFilterButton = QPushButton(
            self.tr('Set'), self.lvWidget)
        self.lvWidgetHLayout2.addWidget(self.setLocalsFilterButton)
        self.lvWidgetVLayout.addLayout(self.lvWidgetHLayout2)
        
        index = self.__tabWidget.addTab(
            self.lvWidget,
            UI.PixmapCache.getIcon("localVariables.png"), '')
        self.__tabWidget.setTabToolTip(index, self.localsViewer.windowTitle())
        
        self.sourceButton.clicked.connect(self.__showSource)
        self.stackComboBox.currentIndexChanged[int].connect(
            self.__frameSelected)
        self.setLocalsFilterButton.clicked.connect(self.__setLocalsFilter)
        self.localsFilterEdit.returnPressed.connect(self.__setLocalsFilter)
        
        from .CallStackViewer import CallStackViewer
        # add the call stack viewer
        self.callStackViewer = CallStackViewer(self.debugServer)
        index = self.__tabWidget.addTab(
            self.callStackViewer,
            UI.PixmapCache.getIcon("step.png"), "")
        self.__tabWidget.setTabToolTip(
            index, self.callStackViewer.windowTitle())
        self.callStackViewer.sourceFile.connect(self.sourceFile)
        self.callStackViewer.frameSelected.connect(
            self.__callStackFrameSelected)
        
        from .CallTraceViewer import CallTraceViewer
        # add the call trace viewer
        self.callTraceViewer = CallTraceViewer(self.debugServer)
        index = self.__tabWidget.addTab(
            self.callTraceViewer,
            UI.PixmapCache.getIcon("callTrace.png"), "")
        self.__tabWidget.setTabToolTip(
            index, self.callTraceViewer.windowTitle())
        self.callTraceViewer.sourceFile.connect(self.sourceFile)
        
        from .BreakPointViewer import BreakPointViewer
        # add the breakpoint viewer
        self.breakpointViewer = BreakPointViewer()
        self.breakpointViewer.setModel(self.debugServer.getBreakPointModel())
        index = self.__tabWidget.addTab(
            self.breakpointViewer,
            UI.PixmapCache.getIcon("breakpoints.png"), '')
        self.__tabWidget.setTabToolTip(
            index, self.breakpointViewer.windowTitle())
        self.breakpointViewer.sourceFile.connect(self.sourceFile)
        
        from .WatchPointViewer import WatchPointViewer
        # add the watch expression viewer
        self.watchpointViewer = WatchPointViewer()
        self.watchpointViewer.setModel(self.debugServer.getWatchPointModel())
        index = self.__tabWidget.addTab(
            self.watchpointViewer,
            UI.PixmapCache.getIcon("watchpoints.png"), '')
        self.__tabWidget.setTabToolTip(
            index, self.watchpointViewer.windowTitle())
        
        from .ExceptionLogger import ExceptionLogger
        # add the exception logger
        self.exceptionLogger = ExceptionLogger()
        index = self.__tabWidget.addTab(
            self.exceptionLogger,
            UI.PixmapCache.getIcon("exceptions.png"), '')
        self.__tabWidget.setTabToolTip(
            index, self.exceptionLogger.windowTitle())
        
        if self.embeddedShell:
            self.__tabWidget.setCurrentWidget(self.shellAssembly)
        else:
            if self.embeddedBrowser:
                self.__tabWidget.setCurrentWidget(self.browser)
            else:
                self.__tabWidget.setCurrentWidget(self.glvWidget)
        
        # add the threads viewer
        self.__mainLayout.addWidget(QLabel(self.tr("Threads:")))
        self.__threadList = QTreeWidget()
        self.__threadList.setHeaderLabels(
            [self.tr("ID"), self.tr("Name"),
             self.tr("State"), ""])
        self.__threadList.setSortingEnabled(True)
        self.__mainLayout.addWidget(self.__threadList)
        
        self.__doThreadListUpdate = True
        
        self.__threadList.currentItemChanged.connect(self.__threadSelected)
        
        self.__mainLayout.setStretchFactor(self.__tabWidget, 5)
        self.__mainLayout.setStretchFactor(self.__threadList, 1)
        
        self.currPage = None
        self.currentStack = None
        self.framenr = 0
        
        self.debugServer.clientStack.connect(self.handleClientStack)
        
        self.__autoViewSource = Preferences.getDebugger("AutoViewSourceCode")
        self.sourceButton.setVisible(not self.__autoViewSource)
        
    def preferencesChanged(self):
        """
        Public slot to handle the preferencesChanged signal.
        """
        self.__autoViewSource = Preferences.getDebugger("AutoViewSourceCode")
        self.sourceButton.setVisible(not self.__autoViewSource)
        
    def setDebugger(self, debugUI):
        """
        Public method to set a reference to the Debug UI.
        
        @param debugUI reference to the DebugUI object (DebugUI)
        """
        self.debugUI = debugUI
        self.debugUI.clientStack.connect(self.handleClientStack)
        self.callStackViewer.setDebugger(debugUI)
        
    def handleResetUI(self):
        """
        Public method to reset the SBVviewer.
        """
        self.globalsViewer.handleResetUI()
        self.localsViewer.handleResetUI()
        self.__setGlobalsFilter()
        self.__setLocalsFilter()
        self.sourceButton.setEnabled(False)
        self.currentStack = None
        self.stackComboBox.clear()
        self.__threadList.clear()
        if self.embeddedShell:
            self.__tabWidget.setCurrentWidget(self.shellAssembly)
        else:
            if self.embeddedBrowser:
                self.__tabWidget.setCurrentWidget(self.browser)
            else:
                self.__tabWidget.setCurrentWidget(self.glvWidget)
        self.breakpointViewer.handleResetUI()
        
    def handleRawInput(self):
        """
        Public slot to handle the switch to the shell in raw input mode.
        """
        if self.embeddedShell:
            self.saveCurrentPage()
            self.__tabWidget.setCurrentWidget(self.shellAssembly)
        
    def initCallStackViewer(self, projectMode):
        """
        Public method to initialize the call stack viewer.
        
        @param projectMode flag indicating to enable the project mode (boolean)
        """
        self.callStackViewer.clear()
        self.callStackViewer.setProjectMode(projectMode)
        
    def isCallTraceEnabled(self):
        """
        Public method to get the state of the call trace function.
        
        @return flag indicating the state of the call trace function (boolean)
        """
        return self.callTraceViewer.isCallTraceEnabled()
        
    def clearCallTrace(self):
        """
        Public method to clear the recorded call trace.
        """
        self.callTraceViewer.clear()
        
    def setCallTraceToProjectMode(self, enabled):
        """
        Public slot to set the call trace viewer to project mode.
        
        In project mode the call trace info is shown with project relative
        path names.
        
        @param enabled flag indicating to enable the project mode (boolean)
        """
        self.callTraceViewer.setProjectMode(enabled)
        
    def showVariables(self, vlist, globals):
        """
        Public method to show the variables in the respective window.
        
        @param vlist list of variables to display
        @param globals flag indicating global/local state
        """
        if globals:
            self.globalsViewer.showVariables(vlist, self.framenr)
        else:
            self.localsViewer.showVariables(vlist, self.framenr)
            
    def showVariable(self, vlist, globals):
        """
        Public method to show the variables in the respective window.
        
        @param vlist list of variables to display
        @param globals flag indicating global/local state
        """
        if globals:
            self.globalsViewer.showVariable(vlist)
        else:
            self.localsViewer.showVariable(vlist)
            
    def showVariablesTab(self, globals):
        """
        Public method to make a variables tab visible.
        
        @param globals flag indicating global/local state
        """
        if globals:
            self.__tabWidget.setCurrentWidget(self.glvWidget)
        else:
            self.__tabWidget.setCurrentWidget(self.lvWidget)
        
    def saveCurrentPage(self):
        """
        Public slot to save the current page.
        """
        self.currPage = self.__tabWidget.currentWidget()
        
    def restoreCurrentPage(self):
        """
        Public slot to restore the previously saved page.
        """
        if self.currPage is not None:
            self.__tabWidget.setCurrentWidget(self.currPage)
            
    def handleClientStack(self, stack):
        """
        Public slot to show the call stack of the program being debugged.
        
        @param stack list of tuples with call stack data (file name,
            line number, function name, formatted argument/values list)
        """
        block = self.stackComboBox.blockSignals(True)
        self.framenr = 0
        self.stackComboBox.clear()
        self.currentStack = stack
        self.sourceButton.setEnabled(len(stack) > 0)
        for s in stack:
            # just show base filename to make it readable
            s = (os.path.basename(s[0]), s[1], s[2])
            self.stackComboBox.addItem('{0}:{1}:{2}'.format(*s))
        self.stackComboBox.blockSignals(block)
        
    def setVariablesFilter(self, globalsFilter, localsFilter):
        """
        Public slot to set the local variables filter.
        
        @param globalsFilter filter list for global variable types
            (list of int)
        @param localsFilter filter list for local variable types (list of int)
        """
        self.globalsFilter = globalsFilter
        self.localsFilter = localsFilter
        
    def __showSource(self):
        """
        Private slot to handle the source button press to show the selected
        file.
        """
        index = self.stackComboBox.currentIndex()
        if index > -1 and self.currentStack:
            s = self.currentStack[index]
            self.sourceFile.emit(s[0], int(s[1]))
        
    def __frameSelected(self, frmnr):
        """
        Private slot to handle the selection of a new stack frame number.
        
        @param frmnr frame number (0 is the current frame) (int)
        """
        self.framenr = frmnr
        self.debugServer.remoteClientVariables(0, self.localsFilter, frmnr)
        
        if self.__autoViewSource:
            self.__showSource()
        
    def __setGlobalsFilter(self):
        """
        Private slot to set the global variable filter.
        """
        filter = self.globalsFilterEdit.text()
        self.debugServer.remoteClientSetFilter(1, filter)
        self.debugServer.remoteClientVariables(2, self.globalsFilter)
        
    def __setLocalsFilter(self):
        """
        Private slot to set the local variable filter.
        """
        filter = self.localsFilterEdit.text()
        self.debugServer.remoteClientSetFilter(0, filter)
        if self.currentStack:
            self.debugServer.remoteClientVariables(
                0, self.localsFilter, self.framenr)
        
    def handleDebuggingStarted(self):
        """
        Public slot to handle the start of a debugging session.
        
        This slot sets the variables filter expressions.
        """
        self.__setGlobalsFilter()
        self.__setLocalsFilter()
        self.showVariablesTab(False)
        
    def currentWidget(self):
        """
        Public method to get a reference to the current widget.
        
        @return reference to the current widget (QWidget)
        """
        return self.__tabWidget.currentWidget()
        
    def setCurrentWidget(self, widget):
        """
        Public slot to set the current page based on the given widget.
        
        @param widget reference to the widget (QWidget)
        """
        self.__tabWidget.setCurrentWidget(widget)
        
    def showThreadList(self, currentID, threadList):
        """
        Public method to show the thread list.
        
        @param currentID id of the current thread (integer)
        @param threadList list of dictionaries containing the thread data
        """
        citm = None
        
        self.__threadList.clear()
        for thread in threadList:
            if thread['broken']:
                state = self.tr("waiting at breakpoint")
            else:
                state = self.tr("running")
            itm = QTreeWidgetItem(self.__threadList,
                                  ["{0:d}".format(thread['id']),
                                   thread['name'], state])
            if thread['id'] == currentID:
                citm = itm
        
        self.__threadList.header().resizeSections(QHeaderView.ResizeToContents)
        self.__threadList.header().setStretchLastSection(True)
        
        if citm:
            self.__doThreadListUpdate = False
            self.__threadList.setCurrentItem(citm)
            self.__doThreadListUpdate = True
        
    def __threadSelected(self, current, previous):
        """
        Private slot to handle the selection of a thread in the thread list.
        
        @param current reference to the new current item (QTreeWidgetItem)
        @param previous reference to the previous current item
            (QTreeWidgetItem)
        """
        if current is not None and self.__doThreadListUpdate:
            tid = int(current.text(0))
            self.debugServer.remoteSetThread(tid)
    
    def __callStackFrameSelected(self, frameNo):
        """
        Private slot to handle the selection of a call stack entry of the
        call stack viewer.
        
        @param frameNo frame number (index) of the selected entry (integer)
        """
        if frameNo >= 0:
            self.stackComboBox.setCurrentIndex(frameNo)
Esempio n. 20
0
    def initUI(self):

        cnum = QLabel('课程号:    ')
        self.cnumInput = QLineEdit()

        cname = QLabel('课程名:   ')
        self.cnameInput = QLineEdit()

        tname = QLabel('教师:     ')
        self.tnameInput = QLineEdit()

        ctime = QLabel('上课时间:')
        self.ctimeInput = QLineEdit()

        self.searchbtn = QPushButton('查询', self)
        self.searchbtn.setIcon(QIcon('./image/find.png'))
        self.searchbtn.clicked.connect(self.onSearch)

        vbox1 = QVBoxLayout()
        vbox1.addWidget(cnum)
        vbox1.addWidget(cname)

        vbox2 = QVBoxLayout()
        vbox2.addWidget(self.cnumInput)
        vbox2.addWidget(self.cnameInput)

        vbox3 = QVBoxLayout()
        vbox3.addWidget(tname)
        vbox3.addWidget(ctime)

        vbox4 = QVBoxLayout()
        vbox4.addWidget(self.tnameInput)
        vbox4.addWidget(self.ctimeInput)

        hbox1 = QHBoxLayout()
        hbox1.addLayout(vbox1)
        hbox1.addLayout(vbox2)
        hbox1.addStretch(1)
        hbox1.addLayout(vbox3)
        hbox1.addLayout(vbox4)

        hbox1.setStretchFactor(vbox1, 1)
        hbox1.setStretchFactor(vbox2, 3)
        hbox1.setStretchFactor(vbox3, 1)
        hbox1.setStretchFactor(vbox4, 3)

        hbox2 = QHBoxLayout()
        hbox2.addStretch(1)
        hbox2.addWidget(self.searchbtn)
        hbox2.addStretch(1)

        vbox5 = QVBoxLayout()
        vbox5.addLayout(hbox1)
        vbox5.addLayout(hbox2)

        self.centerframe = QFrame(self)
        self.centerframe.setFrameShape(QFrame.StyledPanel)

        self.centerLayout = QVBoxLayout(self)
        self.centerframe.setLayout(self.centerLayout)

        self.msg = QLabel(self)
        
        self.rownum = 0
        self.showtable = None
        self.rbtns = []
        self.bottom = None

        total = QVBoxLayout(self)
        total.addLayout(vbox5)
        total.addWidget(self.centerframe)
        total.setStretchFactor(vbox5, 1)
        total.setStretchFactor(self.centerframe, 3)
        self.setLayout(total)
Esempio n. 21
0
class DiceGameWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=parent)
        self.parent = parent
        #self.setStyleSheet("background-color:#BD0000;")
        self.build_ui()
        

    
    def build_ui(self):
        self.main_vbox = QVBoxLayout()
        
        self.build_header_box()
        self.build_roll_choice_box()
        self.build_roll_Equal_NEqual()
        self.build_roll_under_over()
        self.build_roll_even_odd()
        self.build_dice_history_list()

        self.main_vbox.addStretch()
        self.setLayout(self.main_vbox)

    def build_header_box(self):
        header_widget = DiceHeaderWidget(self)
        self.main_vbox.addWidget(header_widget)
        
    def build_roll_choice_box(self):

        self.btn_choice_E_NE = QPushButton("Equal/Not Equal")
        self.btn_choice_U_O = QPushButton("Under/Over")
        self.btn_choice_E_O = QPushButton("Even/Odd")

        self.btn_choice_E_NE.clicked.connect(lambda: self.flip_roll_control_visibility("E_NE"))
        self.btn_choice_U_O.clicked.connect(lambda: self.flip_roll_control_visibility("U_O"))
        self.btn_choice_E_O.clicked.connect(lambda: self.flip_roll_control_visibility("E_O"))

        self.btn_choice_E_NE.setStyleSheet("background-color:#CA2626;color:white")
        self.btn_choice_U_O.setStyleSheet("background-color:#CA2626;color:white")
        self.btn_choice_E_O.setStyleSheet("background-color:#CA2626;color:white")

        self.btn_choice_E_NE.setFixedHeight(50)
        self.btn_choice_U_O.setFixedHeight(50)
        self.btn_choice_E_O.setFixedHeight(50)
        
        self.roll_choice_grid = QGridLayout()
        self.roll_choice_grid.addWidget(self.btn_choice_E_NE,0,0)
        self.roll_choice_grid.addWidget(self.btn_choice_U_O,0,1)
        self.roll_choice_grid.addWidget(self.btn_choice_E_O,0,2)
        
        self.line = QFrame();
        self.line.setFrameShape(QFrame.HLine);
        self.line.setFrameShadow(QFrame.Sunken);

        self.lbl_roll_title = QLabel("")
        self.lbl_roll_title.setStyleSheet("font-size:20pt;font-weight:bold;color:#CA2626")
        self.lbl_roll_title.setAlignment(Qt.AlignCenter)

        self.main_vbox.addLayout(self.roll_choice_grid)
        self.main_vbox.addWidget(self.line)
        self.main_vbox.addWidget(self.lbl_roll_title)

    def build_roll_Equal_NEqual(self):
         self.roll_equal_not_equal = Equal_NotEqual(self.parent)
         self.main_vbox.addWidget(self.roll_equal_not_equal)
         self.roll_equal_not_equal.setVisible(False)
       
    def build_roll_under_over(self):
        self.roll_under_over = Total_Under_Over(self.parent)
        self.main_vbox.addWidget(self.roll_under_over)
        self.roll_under_over.setVisible(False)
       
    def build_roll_even_odd(self):
        self.roll_odd_even = Odd_Even(self.parent)
        self.main_vbox.addWidget(self.roll_odd_even)
        self.roll_odd_even.setVisible(False)
       
        

    def flip_roll_control_visibility(self, choice):
        self.current_roll_type = choice
        if choice == "E_NE":
            
            self.roll_equal_not_equal.setVisible(True)
            self.lbl_roll_title.setText("Roll Equal/Not Equal")
            
            self.roll_under_over.setVisible(False)
            self.roll_odd_even.setVisible(False)
        elif choice == "U_O":
            self.roll_under_over.setVisible(True)
            self.lbl_roll_title.setText("Roll Under/Over")

            self.roll_equal_not_equal.setVisible(False)
            self.roll_odd_even.setVisible(False)
        elif choice == "E_O":
            self.roll_odd_even.setVisible(True)
            self.lbl_roll_title.setText("Roll Even/Odd")

            self.roll_equal_not_equal.setVisible(False)
            self.roll_under_over.setVisible(False)
        self.reset_roll_buttonGroup()

    def reset_roll_buttonGroup(self):
        self.roll_equal_not_equal.reset_button_group()
        self.roll_under_over.reset_button_group()
    
    def build_dice_history_list(self):
        dice_history_list = self.parent.create_dice_history_grid()
        self.main_vbox.addWidget(dice_history_list)
        self.main_vbox.setStretchFactor(dice_history_list, 1000)
Esempio n. 22
0
class MainWindow(QWidget):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.setObjectName('MainWindow')

        # set attributes of window
        # self.setMinimumSize(1200, 700)
        self.center()
        self.setStyleSheet(GetQssFile.readQss('../resource/qss/menu.qss'))
        # self.setWindowIcon(QIcon())

        # fight visualization
        self.fightview = None
        self.list_widget = None
        self.list_items = None

        # set main layout
        self.main_layout = QVBoxLayout(self, spacing=0)
        self.main_layout.setContentsMargins(0, 0, 0, 0)
        # set top layout:
        self.top_layout = QVBoxLayout()
        self.main_layout.addLayout(self.top_layout)
        self.setTopLayout()
        # set line
        self.line = QSplitter(Qt.Horizontal)
        self.line.setHandleWidth(10)
        self.main_layout.addWidget(self.line)
        # set bottom layout
        self.bottom_layout = QHBoxLayout()
        self.main_layout.addLayout(self.bottom_layout)
        self.setBottomLayout()
        # the stretch of top layout and bottom layout
        self.main_layout.setStretchFactor(self.top_layout, 1)
        self.main_layout.setStretchFactor(self.bottom_layout, 15)

        # initialize of global information
        globalInformation.init()

    def center(self):
        screen = QDesktopWidget().screenGeometry()
        geometry = self.geometry()
        self.move((screen.width() - geometry.width()) / 2,
                  (screen.height() - geometry.height()) / 2)

    def setTopLayout(self):
        # list menu
        self.list_widget = QListWidget()
        self.list_widget.setMinimumHeight(25)
        self.list_widget.setFlow(QListWidget.LeftToRight)
        self.list_widget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.list_widget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.list_widget.setFrameShape(QListWidget.NoFrame)
        # list item for menu
        self.list_items = QStackedWidget()

        self.top_layout.addWidget(self.list_widget)
        self.top_layout.addWidget(self.list_items)
        self.top_layout.setStretchFactor(self.list_widget, 1)
        self.top_layout.setStretchFactor(self.list_items, 3)

        self.list_widget.currentRowChanged.connect(
            self.list_items.setCurrentIndex)
        self.list_widget.currentRowChanged.connect(
            self.item_choose)
        self.list_str = [
            strings.PATTERN,
            strings.OPERATIONAL_PLANNING,
            strings.MAPS,
            strings.REPLAY,
            strings.SITUATION_INFORMATION,
            strings.MODEL_TRAIN]
        self.item_view = [
            strings.CLASS_PATTERN,
            strings.CLASS_OPERATIONAL_PLANNING,
            strings.CLASS_MAPS,
            strings.CLASS_REPLAY,
            strings.CLASS_SITUATION_INFORMATION,
            strings.CLASS_MODEL_TRAIN]
        for i in range(len(self.list_str)):
            font = QFont()
            font.setBold(True)
            font.setWeight(50)
            font.setPixelSize(14)
            # add item to menu
            item = QListWidgetItem(self.list_str[i], self.list_widget)
            item.setFont(font)
            item.setTextAlignment(Qt.AlignCenter)
            if i == 0:
                item.setSelected(True)
            self.list_items.addWidget(eval(self.item_view[i]))

    def setBottomLayout(self):
        self.fightview = FightView()
        self.bottom_layout.addWidget(self.fightview)

    def item_choose(self):
        message = self.list_str[self.list_widget.currentRow()]
        log = logging.getLogger('StarCraftII')
        log.info('item change: {}'.format(message))
        Signal.get_signal().emit_signal_str('item change: {}'.format(message))
Esempio n. 23
0
class VideoPRWidget(QWidget):

    def __init__(self, fwind):
        super().__init__()

        self.fWindow = fwind

        self.cap = None
        self.timer = None
        self.playState = PlayState.STOP
        self.videoType = None
        self.videoFile = None

        self.cap_frames_count = 0
        self.cap_currentframe = 0
        self.cap_fps = 0
        self.cap_width = 0
        self.cap_height = 0

        self.cvimg = None
        self.qimg = None
        self.platelist = []

        self.initUI()

    def initUI(self):
        """-------------------- topLayout------------------------"""
        self.btn_return = QPushButton("<-")
        self.btn_return.setFixedSize(30, 30)
        self.btn_return.setStatusTip("Return index page")
        self.btn_return.clicked.connect(self.on_btn_return_clicked)

        self.label_RunningMSG = QLabel()
        self.label_RunningMSG.setAlignment(Qt.AlignCenter)

        self.topLayout = QHBoxLayout()
        self.topLayout.addWidget(self.btn_return)
        self.topLayout.addWidget(self.label_RunningMSG)

        """-------------------imgLabel-------------------------"""
        self.openLabel = QLabel()
        self.openLabel.setFixedSize(160, 52)

        self.btn_Open = QPushButton('Open', self.openLabel)
        self.btn_Open.setFixedSize(80, 42)
        self.btn_Open.move(0, 0)
        self.btn_Open.clicked.connect(self.on_btn_Open_clicked)

        self.combobox_Open = QComboBox(self.openLabel)
        self.combobox_Open.addItems(['File', 'URL', 'Camera'])
        self.combobox_Open.setFixedSize(80, 40)
        self.combobox_Open.move(79, 1)
        self.combobox_Open.setStatusTip('Set the video type')

        self.imglayout = QHBoxLayout()
        self.imglayout.setAlignment(Qt.AlignCenter)
        self.imglayout.addWidget(self.openLabel)

        self.imgLabel = VideoPRLabel(self)
        self.imgLabel.setAlignment(Qt.AlignCenter)
        self.imgLabel.setMaximumSize(10000, 10000)
        self.imgLabel.setStyleSheet("QLabel{background-color:black;}")
        self.imgLabel.setLayout(self.imglayout)

        """-------------------- videoOPlayout------------------------"""
        self.btn_Play = QPushButton('Play')
        self.btn_Play.clicked.connect(self.playPlayer)

        self.btn_Pause = QPushButton('Pause')
        self.btn_Pause.clicked.connect(self.pausePlayer)

        self.btn_Stop = QPushButton('Stop')
        self.btn_Stop.clicked.connect(self.stopPlayer)

        self.btn_LastFrame = QPushButton('<')
        self.btn_LastFrame.setFixedWidth(30)
        self.btn_LastFrame.clicked.connect(self.lastFrame)

        self.btn_NextFrame = QPushButton('>')
        self.btn_NextFrame.setFixedWidth(30)
        self.btn_NextFrame.clicked.connect(self.nextFrame)

        self.sld_Frame = QSlider(Qt.Horizontal)
        self.sld_Frame.valueChanged[int].connect(self.frameSlidValueChange)

        self.videoOPlayout = QHBoxLayout()
        self.videoOPlayout.addWidget(self.btn_Play)
        self.videoOPlayout.addWidget(self.btn_Pause)
        self.videoOPlayout.addWidget(self.btn_Stop)
        self.videoOPlayout.addWidget(self.btn_LastFrame)
        self.videoOPlayout.addWidget(self.sld_Frame)
        self.videoOPlayout.addWidget(self.btn_NextFrame)

        self.videoOPlayout.setAlignment(Qt.AlignLeft)

        """-------------------- prOPlayout------------------------"""
        self.cb_Recognize = QCheckBox("Recognize")

        self.label_RecognizeMSG = QLabel()
        self.label_RecognizeMSG.setAlignment(Qt.AlignCenter)

        self.prOPlayout = QHBoxLayout()
        self.prOPlayout.setAlignment(Qt.AlignLeft)

        self.prOPlayout.addWidget(self.cb_Recognize)
        self.prOPlayout.addWidget(self.label_RecognizeMSG)
        self.prOPlayout.setStretchFactor(self.label_RecognizeMSG, 1)

        """-------------------- prSetlayout------------------------"""
        self.cb_debug = QCheckBox("Debug")
        self.cb_label = QCheckBox("Label")

        self.label_DetectType = QLabel(' DetectType')
        self.combobox_DetectType = QComboBox()
        self.combobox_DetectType.addItems(
            ['SOBEL', 'COLOR', 'CMSER', 'SOBEL&COLOR', 'SOBEL&CMSER', 'COLOR&CMSER', 'All'])
        self.combobox_DetectType.setStatusTip('Set the detect type')

        self.label_MaxPlates = QLabel(' MaxPlates')
        self.spinbox_MaxPlates = QSpinBox()
        self.spinbox_MaxPlates.setMinimum(1)
        self.spinbox_MaxPlates.setMaximum(10)
        self.spinbox_MaxPlates.setStatusTip('Set the number of max plates')

        self.prSetlayout = QHBoxLayout()
        self.prSetlayout.setAlignment(Qt.AlignLeft)

        self.prSetlayout.addWidget(self.cb_debug)
        self.prSetlayout.addWidget(self.cb_label)
        self.prSetlayout.addWidget(self.label_DetectType)
        self.prSetlayout.addWidget(self.combobox_DetectType)
        self.prSetlayout.addWidget(self.label_MaxPlates)
        self.prSetlayout.addWidget(self.spinbox_MaxPlates)
        self.prSetlayout.addStretch(1)

        """-------------------- vlayout------------------------"""
        self.vlayout = QVBoxLayout()
        self.vlayout.addLayout(self.topLayout)
        self.vlayout.addWidget(self.imgLabel)
        self.vlayout.setStretchFactor(self.imgLabel, 1)
        self.vlayout.addLayout(self.videoOPlayout)
        self.vlayout.addLayout(self.prOPlayout)
        self.vlayout.addLayout(self.prSetlayout)

        self.setLayout(self.vlayout)

        self.initButton()

    @pyqtSlot(bool)
    def on_btn_return_clicked(self, checked):
        self.fWindow.on_indexAct_clicked()

    def on_btn_Open_clicked(self):
        index = self.combobox_Open.currentIndex()

        if index == 0:

            self.videoFile = QFileDialog.getOpenFileName(self, "OpenFile", "./resources/vidoe",
                                                         "Video File(*.mp4 *.avi *.rmvb *.mkv *.flv)")[0]
            if len(self.videoFile) == 0:
                return
            if self.OpenVideo():
                self.videoType = VideoType.VIDEOFILE
                self.initPlayer()
                self.fWindow.statusBar().showMessage('Video open success!')
            else:
                self.fWindow.statusBar().showMessage('Video open faild!')

        elif index == 1:
            self.videoFile, ok = QInputDialog.getText(self, 'URL', 'Input the URL:')
            if ok:
                if self.OpenVideo():
                    self.videoType = VideoType.URL
                    self.initPlayer()
                    self.fWindow.statusBar().showMessage('URL open success!')
                else:
                    self.fWindow.statusBar().showMessage('URL open faild!')
        else:

            self.videoFile, ok = QInputDialog.getInt(self, 'Camera Port', 'Input the camera port:', 0, 0, 100, 1)
            if ok:
                if self.OpenVideo():
                    self.videoType = VideoType.CAM
                    self.initPlayer()
                    self.fWindow.statusBar().showMessage('Camera open success!')
                else:
                    self.fWindow.statusBar().showMessage('Camera open faild!')

    def OpenVideo(self):
        self.cap = cv2.VideoCapture(self.videoFile)
        if not self.cap.isOpened():
            return False
        return True

    def initButton(self):
        self.btn_Play.setEnabled(False)
        self.btn_Pause.setEnabled(False)
        self.btn_Stop.setEnabled(False)
        self.btn_LastFrame.setEnabled(False)
        self.btn_NextFrame.setEnabled(False)
        self.sld_Frame.setEnabled(False)
        self.sld_Frame.setValue(0)

    def initPlayer(self):

        self.cap_width = self.cap.get(3)
        self.cap_height = self.cap.get(4)
        self.cap_fps = 30

        self.btn_Pause.setEnabled(True)
        self.btn_Stop.setEnabled(True)

        if self.videoType == VideoType.VIDEOFILE:
            self.cap_fps = self.cap.get(5)
            self.cap_frames_count = self.cap.get(7)
            self.btn_LastFrame.setEnabled(True)
            self.btn_NextFrame.setEnabled(True)
            self.sld_Frame.setEnabled(True)
            self.sld_Frame.setMaximum(self.cap_frames_count)

        self.timer = QBasicTimer()
        self.timer.start(1000 / self.cap_fps, self)

        self.playState = PlayState.PLAY
        self.openLabel.hide()

    def stopPlayer(self):
        if self.cap.isOpened():
            self.cap.release()
        self.imgLabel.clear()
        self.openLabel.show()
        self.initButton()
        self.label_RunningMSG.setText('')
        self.label_RecognizeMSG.setText('')
        self.playState = PlayState.STOP
        self.timer.stop()

    def pausePlayer(self):
        if self.playState == PlayState.PLAY:
            self.playState = PlayState.PAUSE
            self.btn_Pause.setEnabled(False)
            self.btn_Play.setEnabled(True)

    def playPlayer(self):
        if self.playState == PlayState.PAUSE:
            self.playState = PlayState.PLAY
            self.btn_Play.setEnabled(False)
            self.btn_Pause.setEnabled(True)

    def updateFrame(self):
        ret, self.cvimg = self.cap.read()

        if ret:
            cvtemp = numpy.copy(self.cvimg)
            self.qimg = CV2QImage(self.cvimg)

            if self.cb_Recognize.isChecked():

                self.fWindow.plateRecognize.setDebug(self.cb_debug.isChecked())
                self.fWindow.plateRecognize.setDetectType(self.combobox_DetectType.currentIndex())
                self.fWindow.plateRecognize.setMaxPlates(self.spinbox_MaxPlates.value())

                begin = time()
                self.platelist = self.fWindow.plateRecognize.plateRecognize(cvtemp)
                end = time()
                runtime = end - begin

                if self.cb_label.isChecked():
                    for i in range(len(self.platelist)):
                        license, x, y, w, h = self.platelist[i]
                        cvtemp = cv2.rectangle(cvtemp, (x, y),
                                             (x + w, y + h), (0, 255, 0), 2)

                self.label_RecognizeMSG.setText(
                    'Found {plates} plate.   Runtime:{runtime:.3f}s'.format(plates=len(self.platelist),
                                                                            runtime=runtime))

            qtemp = CV2QImage(cvtemp)
            self.imgLabel.setPixmap(QPixmap.fromImage(qtemp))

            if self.videoType == VideoType.VIDEOFILE:
                self.cap_currentframe = self.cap.get(1)
                self.sld_Frame.setValue(self.cap_currentframe)

            self.label_RunningMSG.setText(
                'Frames:{current_frame}/{frames_count}  FPS:{fps}   Width:{width}    Height:{height}'.format( \
                    current_frame=self.cap_currentframe, \
                    frames_count=self.cap_frames_count, \
                    fps=self.cap_fps, \
                    width=self.cap_width, \
                    height=self.cap_height))

    def frameSlidValueChange(self, value):
        if value != self.cap_currentframe:
            self.cap_currentframe = value
            self.cap.set(1, self.cap_currentframe)
            self.updateFrame()

    def lastFrame(self):
        if self.cap_currentframe > 0:
            self.sld_Frame.setValue(self.cap_currentframe - 2)
            self.pausePlayer()

    def nextFrame(self):
        if self.cap_currentframe < self.cap_frames_count - 3:
            self.sld_Frame.setValue(self.cap_currentframe + 1)
            self.pausePlayer()

    def hide(self):
        if self.playState != PlayState.STOP:
            self.timer.stop()
            self.stopPlayer()
        super().hide()

    def show(self):
        self.openLabel.show()
        super().show()

    def timerEvent(self, event):
        if event.timerId() == self.timer.timerId():

            if self.playState == PlayState.PLAY:
                self.updateFrame()

            if self.videoType == VideoType.VIDEOFILE and self.cap_currentframe > self.cap_frames_count - 3:
                self.stopPlayer()

        else:
            super().timerEvent(event)

    def keyPressEvent(self, event):

        key = event.key()

        if key == Qt.Key_Escape:
            self.fWindow.on_indexAct_clicked()
            return

        if key == Qt.Key_Space:
            if self.playState == PlayState.PLAY:
                self.pausePlayer()
            elif self.playState == PlayState.PAUSE:
                self.playPlayer()
            return

        if key == Qt.Key_Left:
            if self.playState != PlayState.STOP and self.videoType == VideoType.VIDEOFILE:
                self.lastFrame()
            return

        if key == Qt.Key_Right:
            if self.playState != PlayState.STOP and self.videoType == VideoType.VIDEOFILE:
                self.nextFrame()
            return

        super().keyPressEvent(event)
Esempio n. 24
0
class ScheduleCourse(QWidget):
    def __init__(self, usr=None, term=None, isstu=True):
        super().__init__()
        self.usr = usr
        self.term = term
        self.isstu = isstu
        self.initUI()

    def initUI(self):

        self.totalLayout = QVBoxLayout()
        #数据获取
        data = util.showSelectCourse(self.usr, self.term, self.isstu)
        #上半部分
        uptip = QLabel()
        ups = ''
        if self.isstu:
            ups = '已选课程:'
        else:
            ups = '已开课程:'
        uptip.setText(ups)
        uptip.setFont(QFont('宋体'))

        self.uplayout = QVBoxLayout()
        self.uplayout.addWidget(uptip)
        self.uptable = None
        self.createUpTable(data)

        self.totalLayout.addLayout(self.uplayout)

        #下半部分
        downtip = QLabel('课程表')
        downtip.setFont(QFont('宋体'))

        self.downlayout = QVBoxLayout()
        self.downlayout.addWidget(downtip)
        self.downtable = None
        self.createDownTable(data)

        self.totalLayout.addLayout(self.downlayout)

        self.totalLayout.setStretchFactor(self.uplayout, 1)
        self.totalLayout.setStretchFactor(self.downlayout, 3)

        self.setLayout(self.totalLayout)

    def createUpTable(self, data):
        if self.uptable is not None:
            self.uplayout.removeWidget(self.uptable)
            sip.delete(self.uptable)
            self.uptable = None

        rownum, colnum = len(data), 0
        if self.isstu:
            colnum = 5
            self.uptable = QTableWidget(rownum, colnum)
            self.uptable.setHorizontalHeaderLabels(
                ['课程号', '课程名', '教师号', '教师', '上课时间'])
        else:
            colnum = 3
            self.uptable = QTableWidget(rownum, colnum)
            self.uptable.setHorizontalHeaderLabels(['课程号', '课程名', '上课时间'])
        for i in range(rownum):
            for j in range(colnum):
                self.uptable.setItem(i, j,
                                     QtWidgets.QTableWidgetItem(data[i][j]))
        self.uptable.horizontalHeader().setSectionResizeMode(
            QtWidgets.QHeaderView.Stretch)
        self.uptable.setEditTriggers(
            QtWidgets.QAbstractItemView.NoEditTriggers)
        self.uptable.setSelectionBehavior(
            QtWidgets.QAbstractItemView.SelectRows)

        self.uplayout.addWidget(self.uptable)

    def createDownTable(self, data):
        if self.downtable is not None:
            self.downlayout.removeWidget(self.downtable)
            sip.delete(self.downtable)
            self.downtable = None
        rownum = 13
        colnum = 7
        self.downtable = QTableWidget(rownum, colnum)
        self.downtable.setHorizontalHeaderLabels(
            ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'])
        for x in data:
            time = x[-1]
            res = util.getclasstime(time)
            for y in res:
                self.downtable.setItem(y[1] - 1, y[0],
                                       QtWidgets.QTableWidgetItem(x[1]))
                self.downtable.setSpan(y[1] - 1, y[0], y[2] - y[1] + 1,
                                       1)  #单元格合并
        self.downtable.horizontalHeader().setSectionResizeMode(
            QtWidgets.QHeaderView.Stretch)
        self.downtable.setEditTriggers(
            QtWidgets.QAbstractItemView.NoEditTriggers)

        self.downlayout.addWidget(self.downtable)
class LogInspectorWindow(QMainWindow):
    def __init__(self, configFilePath, parent=None):
        super(LogInspectorWindow, self).__init__(parent)
        self.initMatPlotLib()
        self.configFilePath = configFilePath

        folder = os.path.dirname(self.configFilePath)
        if not os.path.exists(folder):
            os.makedirs(folder)

        if os.path.exists(self.configFilePath):
            # config.yaml found.  Read from file.
            file = open(self.configFilePath, 'r')
            self.config = yaml.safe_load(file)
            file.close()
        else:
            # config.yaml not found.  Create new file.
            self.config = {}
            self.config['logs_directory'] = os.path.join(
                os.path.expanduser("~"), "Documents", "Inertial_Sense", "Logs")
            self.config['directory'] = ""
            self.config['serials'] = ["ALL"]
            file = open(self.configFilePath, 'w')
            yaml.dump(self.config, file)
            file.close()

        self.currently_selected = 'posNEDMap'
        self.downsample = 5
        self.plotargs = None
        self.log = None
        self.plotter = None

    def initMatPlotLib(self):
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.figure.subplots_adjust(left=0.05,
                                    right=0.99,
                                    bottom=0.05,
                                    top=0.91,
                                    wspace=0.2,
                                    hspace=0.2)

    def addButton(self, name, function, multithreaded=True, layout=None):
        setattr(self, name + "button", QPushButton(name))
        # if multithreaded:
        # setattr(self, name+"buttonThread", Thread(target=function))
        # getattr(self, name+"button").pressed.connect(self.startLoadingIndicator)
        # getattr(self, name+"button").released.connect(getattr(self, name+"buttonThread").start)
        # else:
        getattr(self, name + "button").clicked.connect(function)
        # getattr(self, name + "button").setMinimumWidth(220)
        if layout is None:
            if self.buttonLayoutRightCol.count(
            ) < self.buttonLayoutMiddleCol.count():
                self.buttonLayoutRightCol.addWidget(
                    getattr(self, name + "button"))
            elif self.buttonLayoutMiddleCol.count(
            ) < self.buttonLayoutLeftCol.count():
                self.buttonLayoutMiddleCol.addWidget(
                    getattr(self, name + "button"))
            else:
                self.buttonLayoutLeftCol.addWidget(
                    getattr(self, name + "button"))
        else:
            layout.addWidget(getattr(self, name + "button"))

    def updatePlot(self):
        self.plot(self.currently_selected, self.plotargs)

    def updateWindowTitle(self):
        if np.shape(self.log.data[0, DID_DEV_INFO])[0] != 0:
            info = self.log.data[0, DID_DEV_INFO][0]
            infoStr = 'SN' + str(info[1]) + ', H:' + verArrayToString(
                info[2]) + ', F:' + verArrayToString(
                    info[3]) + ' build ' + str(
                        info[4]) + ', ' + dateTimeArrayToString(
                            info[8], info[9]) + ', ' + info[10].decode('UTF-8')
            self.setWindowTitle("LogInspector  -  " + infoStr)

    def choose_directory(self):
        log_dir = config['logs_directory']
        directory = QFileDialog.getExistingDirectory(
            parent=self, caption='Choose Log Directory', directory=log_dir)

        if directory != '':
            try:
                self.load(directory)
            except Exception as e:
                msg = QMessageBox()
                msg.setIcon(QMessageBox.Critical)
                msg.setText("Unable to load log: " + e.__str__())
                msg.setDetailedText(traceback.format_exc())
                msg.exec()

    def load(self, directory):
        print("loading files from " + directory)
        # if self.log is None:
        self.log = Log()
        self.log.load(directory)
        print("done loading")
        self.plotter = logPlot(False, False, 'svg', self.log)
        self.plotter.setDownSample(self.downsample)
        # str = ''
        # if self.log.navMode:
        #     str += 'NAV '
        # if self.log.rtk:
        #     str += 'RTK '
        # if self.log.compassing:
        #     str += 'Comp '
        # self.statusLabel.setText(str)
        self.updatePlot()
        self.updateWindowTitle()
        self.stopLoadingIndicator()

    def setupUi(self):
        self.setObjectName("LogInspector")
        self.setWindowTitle("LogInspector")
        self.resize(1280, 900)
        self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowSystemMenuHint
                            | QtCore.Qt.WindowMinMaxButtonsHint)
        self.setWindowIcon(QIcon("assets/Magnifying_glass_icon.png"))

        # MainWindow.showMaximized()

        self.createFileTree()
        self.createButtonColumn()
        self.formatButtonColumn()
        self.createBottomToolbar()

        self.figureLayout = QVBoxLayout()
        self.figureLayout.addWidget(self.canvas)
        self.figureLayout.addLayout(self.toolLayout)
        self.figureLayout.setStretchFactor(self.canvas, 1)

        layout = QHBoxLayout()
        layout.addLayout(self.controlLayout)
        layout.addLayout(self.figureLayout)
        layout.setStretch(1, 1)
        widget = QWidget()
        widget.setLayout(layout)
        self.setCentralWidget(widget)
        # self.resize(1280, 900)
        self.resize(1450, 1000)
        self.setAcceptDrops(True)

    def createButtonColumn(self):
        self.controlLayout = QVBoxLayout()
        self.buttonLayoutLeftCol = QVBoxLayout()
        self.buttonLayoutMiddleCol = QVBoxLayout()
        self.buttonLayoutRightCol = QVBoxLayout()
        self.addButton('Pos NED Map', lambda: self.plot('posNEDMap'))
        self.addButton('Pos NED', lambda: self.plot('posNED'))
        self.addButton('Pos LLA', lambda: self.plot('posLLA'))
        self.addButton('GPS LLA', lambda: self.plot('llaGps'))
        self.addButton('Vel NED', lambda: self.plot('velNED'))
        self.addButton('Vel UVW', lambda: self.plot('velUVW'))
        self.addButton('Attitude', lambda: self.plot('attitude'))
        self.addButton('Heading', lambda: self.plot('heading'))
        self.addButton('INS Status', lambda: self.plot('insStatus'))
        self.addButton('HDW Status', lambda: self.plot('hdwStatus'))
        self.addButton('GPS 1 Stats', lambda: self.plot('gpsStats'))
        self.addButton('GPS 2 Stats', lambda: self.plot('gps2Stats'))
        self.addButton('RTK Pos Stats', lambda: self.plot('rtkPosStats'))
        self.addButton('RTK Cmp Stats', lambda: self.plot('rtkCmpStats'))
        self.addButton('Flash Config', lambda: self.showFlashConfig())
        self.addButton('Device Info', lambda: self.showDeviceInfo())
        self.addButton('IMU PQR', lambda: self.plot('imuPQR'))
        self.addButton('IMU Accel', lambda: self.plot('imuAcc'))
        self.addButton('PSD PQR', lambda: self.plot('gyroPSD'))
        self.addButton('PSD Accel', lambda: self.plot('accelPSD'))
        self.addButton('Magnetometer', lambda: self.plot('magnetometer'))
        self.addButton('Temp', lambda: self.plot('temp'))

    def formatButtonColumn(self):
        self.buttonLayoutLeftCol.setAlignment(QtCore.Qt.AlignTop)
        self.buttonLayoutMiddleCol.setAlignment(QtCore.Qt.AlignTop)
        self.buttonLayoutRightCol.setAlignment(QtCore.Qt.AlignTop)
        self.buttonColumnLayout = QHBoxLayout()
        self.buttonColumnLayout.addLayout(self.buttonLayoutLeftCol)
        self.buttonColumnLayout.addLayout(self.buttonLayoutMiddleCol)
        self.buttonColumnLayout.addLayout(self.buttonLayoutRightCol)
        self.controlLayout.addLayout(self.buttonColumnLayout)
        self.controlDirLayout = QHBoxLayout()
        self.controlDirLayout.addWidget(self.dirLineEdit)
        self.controlLayout.addLayout(self.controlDirLayout)
        self.controlLayout.addWidget(self.fileTree)
        # self.buttonLayout.addItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding))
        # self.addButton('load', self.choose_directory, multithreaded=False)

    def createBottomToolbar(self):
        self.toolLayout = QHBoxLayout()
        self.toolLayout.addWidget(self.toolbar)

        self.loadingIndictator = QLabel()
        self.loadingMovie = QMovie('assets/loader.gif')
        self.emptyLoadingPicture = QPicture()
        self.emptyLoadingPicture.load('assets/empty_loader.png')
        self.stopLoadingIndicator()
        self.toolLayout.addWidget(self.loadingIndictator)

        self.toolLayout.addItem(
            QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding))
        # self.toolLayout.addWidget(QSpacerItem(150, 10, QSizePolicy.Expanding))

        self.copyImagePushButton = QPushButton()
        # self.copyImagePushButton.setText("Copy")
        # self.copyImagePushButton.setMinimumWidth(1)
        # self.copyImagePushButton.style().standardIcon(QStyle.SP_DialogOpenButton)
        self.copyImagePushButton.setIcon(self.style().standardIcon(
            QStyle.SP_DialogSaveButton))
        self.toolLayout.addWidget(self.copyImagePushButton)
        self.copyImagePushButton.clicked.connect(self.copyPlotToClipboard)

        downsampleLabel = QLabel()
        downsampleLabel.setText("DS")
        self.downSampleInput = QSpinBox()
        self.downSampleInput.setValue(self.downsample)
        self.toolLayout.addWidget(downsampleLabel)
        self.toolLayout.addWidget(self.downSampleInput)
        self.downSampleInput.valueChanged.connect(self.changeDownSample)

        self.statusLabel = QLabel()
        self.toolLayout.addWidget(self.statusLabel)

    def changeDownSample(self, val):
        self.downsample = val
        self.plotter.setDownSample(self.downsample)
        self.updatePlot()

    def copyPlotToClipboard(self):
        # pixmap = QPixmap.grabWidget(self.canvas)
        # QApplication.clipboard().setPixmap(pixmap)
        # pixmap.save('test.png')

        # store the image in a buffer using savefig(), this has the
        # advantage of applying all the default savefig parameters
        # such as background color; those would be ignored if you simply
        # grab the canvas using Qt
        buf = io.BytesIO()
        self.figure.savefig(buf)

        QApplication.clipboard().setImage(QImage.fromData(buf.getvalue()))
        buf.close()

    def startLoadingIndicator(self):
        self.loadingIndictator.setMovie(self.loadingMovie)
        self.loadingMovie.start()

    def dragEnterEvent(self, e):
        if (e.mimeData().hasUrls()):
            e.acceptProposedAction()

    def dropEvent(self, e):
        try:
            directory = e.mimeData().urls()[0].toLocalFile()
            self.load(directory)
        except Exception as e:
            self.showError(e)

    def showError(self, e):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Critical)
        msg.setText("Unable to load log: " + e.__str__())
        msg.setDetailedText(traceback.format_exc())
        msg.exec()

    def createFileTree(self):
        self.dirModel = QFileSystemModel()
        self.dirModel.setRootPath(self.config["logs_directory"])
        self.dirModel.setFilter(QtCore.QDir.Dirs | QtCore.QDir.NoDotAndDotDot)
        self.dirLineEdit = QLineEdit()
        self.dirLineEdit.setText(self.config["logs_directory"])
        self.dirLineEdit.setFixedHeight(25)
        self.dirLineEdit.returnPressed.connect(self.handleTreeDirChange)
        self.fileTree = QTreeView()
        self.fileTree.setModel(self.dirModel)
        self.fileTree.setRootIndex(
            self.dirModel.index(self.config['logs_directory']))
        self.fileTree.setColumnHidden(1, True)
        self.fileTree.setColumnHidden(2, True)
        self.fileTree.setColumnHidden(3, True)
        self.fileTree.setMinimumWidth(300)
        self.fileTree.clicked.connect(self.handleTreeViewClick)
        self.fileTree.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.fileTree.setSelectionMode(QAbstractItemView.SingleSelection)
        self.fileTree.customContextMenuRequested.connect(
            self.handleTreeViewRightClick)
        # self.populateRMSCheck(self.config['logs_directory'])

    def updateFileTree(self):
        self.dirModel.setRootPath(self.config["logs_directory"])
        self.fileTree.setRootIndex(
            self.dirModel.index(self.config['logs_directory']))

    def populateRMSCheck(self, directory):
        for subdir in os.listdir(directory):
            path = os.path.join(directory, subdir)
            if os.path.isdir(path):
                self.populateRMSCheck(path)
            elif 'RMS' in subdir:
                f = open(path)
                rms_report = f.read()
                p = re.compile(r'(?<=^PASS/FAIL).*\n', re.M)
                line = re.search(p, rms_report).group()
                failed = True if "FAIL" in line else False
                if failed:
                    pass
                else:
                    pass

    def handleTreeDirChange(self):
        self.config["logs_directory"] = self.dirLineEdit.text()
        self.updateFileTree()

        file = open(self.configFilePath, 'w')
        yaml.dump(self.config, file)
        file.close()

    def handleTreeViewClick(self):
        selected_directory = self.fileTree.model().filePath(
            self.fileTree.selectedIndexes()[0])
        for fname in os.listdir(selected_directory):
            if fname.endswith('.dat'):
                try:
                    self.load(selected_directory)
                except Exception as e:
                    self.showError(e)
                break

    def handleTreeViewRightClick(self, event):
        selected_directory = os.path.normpath(self.fileTree.model().filePath(
            self.fileTree.selectedIndexes()[0]))
        menu = QMenu(self)
        copyAction = menu.addAction("Copy path")
        nppActionHot = menu.addAction("Run NPP, HOT start")
        nppActionCold = menu.addAction("Run NPP, COLD start")
        nppActionFactory = menu.addAction("Run NPP, FACTORY start")
        setDataInfoDirHotAction = menu.addAction(
            "Set dataInfo.json directory, HOT start")
        setDataInfoDirColdAction = menu.addAction(
            "Set dataInfo.json directory, COLD start")
        setDataInfoDirFactoryAction = menu.addAction(
            "Set dataInfo.json directory, FACTORY start")
        exploreAction = menu.addAction("Explore folder")
        cleanFolderAction = menu.addAction("Clean folder")
        deleteFolderAction = menu.addAction("Delete folder")
        action = menu.exec_(self.fileTree.viewport().mapToGlobal(event))
        if action == copyAction:
            cb = QApplication.clipboard()
            cb.clear(mode=cb.Clipboard)
            cb.setText(selected_directory, mode=cb.Clipboard)
        if action == nppActionHot:
            cleanFolder(selected_directory)
            setDataInformationDirectory(selected_directory,
                                        startMode=START_MODE_HOT)
            sys.path.insert(1, '../../../../python/src')
            from supernpp.supernpp import SuperNPP
            spp = SuperNPP(selected_directory, self.config['serials'])
            spp.run()
        if action == nppActionCold:
            cleanFolder(selected_directory)
            setDataInformationDirectory(selected_directory,
                                        startMode=START_MODE_COLD)
            sys.path.insert(1, '../../../../python/src')
            from supernpp.supernpp import SuperNPP
            spp = SuperNPP(selected_directory,
                           self.config['serials'],
                           startMode=START_MODE_COLD)
            spp.run()
        if action == nppActionFactory:
            cleanFolder(selected_directory)
            setDataInformationDirectory(selected_directory,
                                        startMode=START_MODE_FACTORY)
            sys.path.insert(1, '../../../../python/src')
            from supernpp.supernpp import SuperNPP
            spp = SuperNPP(selected_directory,
                           self.config['serials'],
                           startMode=START_MODE_FACTORY)
            spp.run()
        if action == setDataInfoDirHotAction:
            setDataInformationDirectory(selected_directory,
                                        startMode=START_MODE_HOT)
        if action == setDataInfoDirColdAction:
            setDataInformationDirectory(selected_directory,
                                        startMode=START_MODE_COLD)
        if action == setDataInfoDirFactoryAction:
            setDataInformationDirectory(selected_directory,
                                        startMode=START_MODE_FACTORY)
        if action == exploreAction:
            openFolderWithFileBrowser(selected_directory)
        if action == cleanFolderAction:
            cleanFolder(selected_directory)
        if action == deleteFolderAction:
            msg = QMessageBox(self)
            msg.setIcon(QMessageBox.Question)
            msg.setText("Are you sure you want to delete this folder?\n\n" +
                        selected_directory)
            msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            result = msg.exec()
            if result == QMessageBox.Yes:
                removeDirectory(selected_directory)

    def stopLoadingIndicator(self):
        self.loadingMovie.stop()
        self.loadingIndictator.clear()
        self.loadingIndictator.setPicture(self.emptyLoadingPicture)

    def showDeviceInfo(self):
        dlg = DeviceInfoDialog(self.log, self)
        dlg.show()
        dlg.exec_()

    def showFlashConfig(self):
        dlg = FlashConfigDialog(self.log, self)
        dlg.show()
        dlg.exec_()

    def plot(self, func, args=None):
        print("plotting " + func)
        self.currently_selected = func
        self.plotargs = args

        self.figure.clear()

        if hasattr(self, 'plotter'):
            if args is not None:
                getattr(self.plotter, func)(*args, self.figure)
            else:
                getattr(self.plotter, func)(self.figure)

        self.canvas.draw()
        self.stopLoadingIndicator()
        print("done plotting")
Esempio n. 26
0
    def init_ui(self):

        top_layout = QVBoxLayout()
        top_layout.setContentsMargins(10, 10, 10, 10)
        top_layout.setSpacing(15)

        #
        # Top "message box" / time remaining
        #
        message_layout = QHBoxLayout()
        self.status_label = QLabel("Waiting for Preparation...")
        self.status_label.setStyleSheet(" font-weight: bold; font-size: 18pt; "
                                        "   color: red;")
        self.status_label.setAlignment(Qt.AlignCenter)
        self.progress_label = QLabel("0.0s (1 / 1)")
        self.progress_label.setStyleSheet(" font-size: 16pt; color: black;")
        self.progress_label.setAlignment(Qt.AlignCenter)
        message_layout.addWidget(self.status_label)
        message_layout.addWidget(self.progress_label)
        message_layout.setStretch(0, 66)
        message_layout.setStretch(1, 33)
        top_layout.addLayout(message_layout)

        #
        # Video player
        #
        video_layout = QHBoxLayout()
        self.video_player = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        video_widget = QVideoWidget()
        self.video_player.setVideoOutput(video_widget)

        video_layout.addWidget(video_widget)

        descrip_layout = QVBoxLayout()
        self.desc_title = QLabel("No Movement")
        self.desc_title.setStyleSheet(
            "border: 4px solid gray; font-weight: bold; font-size: 14pt;")
        self.desc_title.setAlignment(Qt.AlignCenter)
        self.desc_explain = QTextEdit("No description available.")
        self.desc_explain.setStyleSheet(
            "border: 4px solid gray; font-size: 12pt; border-color: black;")
        self.desc_explain.setReadOnly(True)
        descrip_layout.addWidget(self.desc_title)
        descrip_layout.addWidget(self.desc_explain)
        video_layout.addLayout(descrip_layout)

        video_layout.setStretch(0, 66)
        video_layout.setStretch(1, 33)
        top_layout.addLayout(video_layout)

        #
        # Preparation Box
        #
        parameters_box = QGroupBox()
        parameters_box.setTitle("Preparation Phase")
        parameters_box.setObjectName("CollecParamBox")
        parameters_box.setStyleSheet(
            "QGroupBox#CollecParamBox { border: 1px solid gray; border-radius: 7px; margin-top: 2em;"
            "                              font-weight: bold; background-color: #dddddd;}"
            "QGroupBox#CollecParamBox::title { subcontrol-origin: margin; subcontrol-position: top center; "
            " border: 1px solid gray; border-radius: 7px;"
            "padding-left: 10px; "
            "padding-right: 10px;}")
        font = parameters_box.font()
        font.setPointSize(16)
        parameters_box.setFont(font)
        parameters_box.setSizePolicy(QSizePolicy.Expanding,
                                     QSizePolicy.Expanding)
        top_layout.addWidget(parameters_box)

        prep_layout = QHBoxLayout()
        prep_layout.setSpacing(10)
        parameters_box.setLayout(prep_layout)

        #
        # Preparation Box: Model Selection
        #
        model_select = QGridLayout()
        model_select.setContentsMargins(0, 0, 10, 0)
        model_button = QPushButton("Select Model")
        model_button.setStyleSheet("font-weight: bold")
        model_select.addWidget(model_button, 0, 0, 1, 2)

        hline = QFrame()
        hline.setFrameShape(QFrame.HLine)
        hline.setFrameShadow(QFrame.Sunken)
        model_select.addWidget(hline, 1, 0, 1, 2)

        name_title = QLabel("Name")
        model_select.addWidget(name_title, 2, 0)
        samples_title = QLabel("Samples")
        model_select.addWidget(samples_title, 3, 0)

        self.model_name = QLineEdit()
        self.model_name.setReadOnly(True)
        model_select.addWidget(self.model_name, 2, 1)
        self.samples_field = QLineEdit()
        self.samples_field.setReadOnly(True)
        model_select.addWidget(self.samples_field, 3, 1)
        prep_layout.addLayout(model_select)

        model_select.setRowStretch(0, 2)
        model_select.setRowStretch(1, 1)
        model_select.setRowStretch(2, 2)
        model_select.setRowStretch(3, 2)

        # Note: No copy constructors for Qt5 objects...
        vline = QFrame()
        vline.setFrameShape(QFrame.VLine)
        vline.setFrameShadow(QFrame.Sunken)
        vline2 = QFrame()
        vline2.setFrameShape(QFrame.VLine)
        vline2.setFrameShadow(QFrame.Sunken)
        vline3 = QFrame()
        vline3.setFrameShape(QFrame.VLine)
        vline3.setFrameShadow(QFrame.Sunken)
        prep_layout.addWidget(vline)

        #
        # Preparation Box: Generate Noise Model
        #
        noise_layout = QVBoxLayout()
        noise_button = QPushButton("Collect Noise")
        noise_button.setStyleSheet("font-weight: bold")
        noise_layout.addWidget(noise_button)
        collect_title = QLabel("Duration")
        collect_title.setAlignment(Qt.AlignCenter | Qt.AlignBottom)

        hline2 = QFrame()
        hline2.setFrameShape(QFrame.HLine)
        hline2.setFrameShadow(QFrame.Sunken)
        noise_layout.addWidget(hline2)
        noise_layout.addWidget(collect_title)

        self.noise_duration = QLineEdit("15.0")
        self.noise_duration.setAlignment(Qt.AlignCenter)
        noise_layout.addWidget(self.noise_duration)

        prep_layout.addLayout(noise_layout)
        prep_layout.addWidget(vline2)
        noise_layout.setStretch(0, 2)
        noise_layout.setStretch(1, 1)
        noise_layout.setStretch(2, 2)
        noise_layout.setStretch(3, 2)

        #
        # Preparation Box: Devices Connected
        #
        connected_layout = QVBoxLayout()
        connected_title = QLabel("Devices Connected")
        connected_title.setAlignment(Qt.AlignCenter)
        connected_title.setStyleSheet("font-weight: bold")
        connected_layout.addWidget(connected_title)
        self.devices_connected = QPushButton()
        #self.devices_connected.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)

        hline3 = QFrame()
        hline3.setFrameShape(QFrame.HLine)
        hline3.setFrameShadow(QFrame.Sunken)
        connected_layout.addWidget(hline3)
        connected_layout.setStretchFactor(connected_title, 2)
        connected_layout.setStretchFactor(hline3, 1)
        connected_layout.setStretchFactor(self.devices_connected, 4)

        connected_layout.addWidget(self.devices_connected)
        prep_layout.addLayout(connected_layout)
        prep_layout.addWidget(vline3)

        #
        # Online Testing Parameters
        #
        param_layout = QGridLayout()
        test_title = QLabel("Test Parameters")
        test_title.setAlignment(Qt.AlignCenter)
        test_title.setStyleSheet("font-weight: bold")
        param_layout.addWidget(test_title, 0, 0, 1, 2)

        hline4 = QFrame()
        hline4.setFrameShape(QFrame.HLine)
        hline4.setFrameShadow(QFrame.Sunken)
        param_layout.addWidget(hline4, 1, 0, 1, 2)

        self.pred_min_duration = QLineEdit("2.0")
        self.pred_max_duration = QLineEdit("4.0")
        self.min_title = QLabel("<b>(Min)</b> Duration")
        self.max_title = QLabel("<b>(Max)</b> Duration")

        param_layout.addWidget(self.min_title, 2, 0)
        param_layout.addWidget(self.max_title, 3, 0)
        param_layout.addWidget(self.pred_min_duration, 2, 1)
        param_layout.addWidget(self.pred_max_duration, 3, 1)
        prep_layout.addLayout(param_layout)

        #
        # Preparation Phase formatting
        #
        prep_layout.setStretchFactor(model_select, 4)
        prep_layout.setStretchFactor(noise_layout, 2)
        prep_layout.setStretchFactor(connected_layout, 5)
        prep_layout.setStretchFactor(param_layout, 4)

        top_layout.setStretch(0, 1)
        top_layout.setStretch(1, 15)
        top_layout.setStretch(2, 3)

        self.setLayout(top_layout)
Esempio n. 27
0
    def CreateLayout(self):
        hboxMain = QHBoxLayout()
        vboxMainSet = QVBoxLayout()
        vboxDisp = QVBoxLayout()

        gboxPortSet = QGroupBox('串口设置')
        gboxRecvSet = QGroupBox('接收设置')
        gboxSendSet = QGroupBox('发送设置')

        vboxPortSet = QVBoxLayout()
        vboxRecvSet = QVBoxLayout()
        vboxSendSet = QVBoxLayout()

        gridPortSet = QGridLayout()
        hboxOpenClosePort = QHBoxLayout()
        gridRecvSet = QGridLayout()
        hboxAddrSet = QHBoxLayout()
        hboxAutoSend = QHBoxLayout()

        hboxSend = QHBoxLayout()

        hboxMain.addLayout(vboxMainSet)
        hboxMain.addLayout(vboxDisp)
        hboxMain.setStretchFactor(vboxMainSet, 0)
        hboxMain.setStretchFactor(vboxDisp, 1)

        vboxMainSet.addWidget(gboxPortSet)
        vboxMainSet.addWidget(gboxRecvSet)
        vboxMainSet.addWidget(gboxSendSet)
        vboxMainSet.addStretch()

        gboxPortSet.setLayout(vboxPortSet)
        gboxRecvSet.setLayout(vboxRecvSet)
        gboxSendSet.setLayout(vboxSendSet)

        vboxPortSet.addLayout(gridPortSet)
        vboxPortSet.addLayout(hboxOpenClosePort)

        vboxRecvSet.addLayout(gridRecvSet)
        vboxRecvSet.addLayout(hboxAddrSet)

        gridPortSet.addWidget(self.lblPort, 0, 0)
        gridPortSet.addWidget(self.cmbPort, 0, 1)
        gridPortSet.addWidget(self.lblBaud, 1, 0)
        gridPortSet.addWidget(self.cmbBaud, 1, 1)
        gridPortSet.addWidget(self.lblParity, 2, 0)
        gridPortSet.addWidget(self.cmbParity, 2, 1)
        gridPortSet.addWidget(self.lblWordLen, 3, 0)
        gridPortSet.addWidget(self.cmbWordLen, 3, 1)
        gridPortSet.addWidget(self.lblStopBits, 4, 0)
        gridPortSet.addWidget(self.cmbStopBits, 4, 1)

        gridPortSet.setColumnStretch(0, 1)
        gridPortSet.setColumnStretch(1, 3)

        hboxOpenClosePort.addWidget(self.btnOpenPort)
        hboxOpenClosePort.addWidget(self.btnClosePort)

        gridRecvSet.addWidget(self.chcHexRecv, 0, 0)
        gridRecvSet.addWidget(self.chcWrap, 0, 1)
        gridRecvSet.addWidget(self.chcAutoClear)
        gridRecvSet.addWidget(self.btnClear)
        gridRecvSet.addWidget(self.chcAutoSave)

        hboxAddrSet.addWidget(self.lblAddr)
        hboxAddrSet.addWidget(self.txtAddr)
        hboxAddrSet.addWidget(self.btnSaveAs)

        vboxSendSet.addWidget(self.chcHexSend)
        vboxSendSet.addLayout(hboxAutoSend)

        hboxAutoSend.addWidget(self.chcAutoSend)
        hboxAutoSend.addWidget(self.txtAutoSend)
        hboxAutoSend.addWidget(self.lblAutoSend)

        vboxDisp.addWidget(self.txtRecv)
        vboxDisp.addLayout(hboxSend)
        vboxDisp.setStretchFactor(self.txtRecv, 1)
        vboxDisp.setStretchFactor(hboxSend, 0)

        hboxSend.addWidget(self.txtSend)
        hboxSend.addWidget(self.btnSend)

        self.setLayout(hboxMain)
Esempio n. 28
0
    def build_ui(self):
        # Menu Bar
        menu_bar = self.menuBar()
        file_menu = menu_bar.addMenu('File')

        new_menu = QAction('New', self)
        new_menu.setShortcut('Ctrl+N')
        new_menu.triggered.connect(self.new)
        file_menu.addAction(new_menu)

        open_menu = QAction('Open', self)
        open_menu.setShortcut('Ctrl+O')
        open_menu.triggered.connect(self.open)
        file_menu.addAction(open_menu)

        save_menu = QAction('Save', self)
        save_menu.setShortcut('Ctrl+S')
        save_menu.triggered.connect(self.save)
        file_menu.addAction(save_menu)

        edit_menu = menu_bar.addMenu("Edit")

        comment_menu = QAction('Comment', self)
        comment_menu.setShortcut('Ctrl+/')
        comment_menu.triggered.connect(self.comment)
        edit_menu.addAction(comment_menu)

        copy_menu = QAction('Copy', self)
        copy_menu.setShortcut('Ctrl+C')
        copy_menu.triggered.connect(self.copy)
        edit_menu.addAction(copy_menu)

        cut_menu = QAction('Cut', self)
        cut_menu.setShortcut('Ctrl+X')
        cut_menu.triggered.connect(self.cut)
        edit_menu.addAction(cut_menu)

        paste_menu = QAction('Paste', self)
        paste_menu.setShortcut('Ctrl+V')
        paste_menu.triggered.connect(self.paste)
        edit_menu.addAction(paste_menu)

        preference_menu = edit_menu.addMenu('Preferences')

        font_menu = QAction('Font', self)
        font_menu.triggered.connect(self.set_font)
        preference_menu.addAction(font_menu)

        about_menu = menu_bar.addMenu("Help")
        help_menu = QAction("About", self)
        help_menu.setShortcut('F7')
        help_menu.triggered.connect(self.about_app)
        about_menu.addAction(help_menu)

        # Setting a vertical box layout
        vertical_box = QVBoxLayout()  # instantiating the QVBoxLayout
        vertical_box.addWidget(
            self.te_main)  # adding the text editor to layout
        vertical_box.setStretchFactor(self.te_main,
                                      1)  # setting the stretch factor
        vertical_box.setContentsMargins(0, 0, 0, 0)  # setting the margins

        central_widget = QWidget()  # widget to hold the text editor
        central_widget.setLayout(vertical_box)
        self.setCentralWidget(central_widget)
    def __init__(self):
        super(RSSReaderWidget, self).__init__()

        self.feed_file_path = os.path.expanduser(
            "~/.emacs.d/eaf/rss-reader/feeds.json")

        self.feed_area = QWidget()
        self.feed_list = QListWidget()
        self.feed_list.setStyleSheet("""QListWidget{background: #4D5250;}""")
        panel_layout = QVBoxLayout()
        panel_layout.setSpacing(0)
        panel_layout.setContentsMargins(0, 0, 0, 0)
        panel_layout.addWidget(self.feed_list)
        self.feed_area.setLayout(panel_layout)

        self.article_area = QWidget()
        self.article_list = QListWidget()
        self.article_list.verticalScrollBar().setStyleSheet(
            "QScrollBar {width:0px;}")
        article_layout = QVBoxLayout()
        article_layout.setSpacing(0)
        article_layout.setContentsMargins(0, 0, 0, 0)

        self.browser = BrowserView()

        article_layout.addWidget(self.article_list)
        article_layout.addWidget(self.browser)

        article_layout.setStretchFactor(self.article_list, 1)
        article_layout.setStretchFactor(self.browser, 3)

        self.article_area.setLayout(article_layout)

        self.welcome_page = QWidget()
        self.welcome_page_box = QVBoxLayout()
        self.welcome_page_box.setSpacing(10)
        self.welcome_page_box.setContentsMargins(0, 0, 0, 0)

        welcome_title_label = QLabel("Welcome to EAF RSS Reader!")
        welcome_title_label.setFont(QFont('Arial', 24))
        welcome_title_label.setStyleSheet(
            "QLabel {color: black; font-weight: bold; margin: 20px;}")
        welcome_title_label.setAlignment(Qt.AlignHCenter)

        add_subscription_label = QLabel("Press key 'a' to add subscription")
        add_subscription_label.setFont(QFont('Arial', 20))
        add_subscription_label.setStyleSheet("QLabel {color: #333;}")
        add_subscription_label.setAlignment(Qt.AlignHCenter)

        self.welcome_page_box.addStretch(1)
        self.welcome_page_box.addWidget(welcome_title_label)
        self.welcome_page_box.addWidget(add_subscription_label)
        self.welcome_page_box.addStretch(1)

        self.welcome_page.setLayout(self.welcome_page_box)

        self.right_area = QStackedWidget()
        self.right_area.addWidget(self.welcome_page)
        self.right_area.addWidget(self.article_area)

        self.right_area.setCurrentIndex(0)

        hbox = QHBoxLayout()
        hbox.setSpacing(0)
        hbox.setContentsMargins(0, 0, 0, 0)

        hbox.addWidget(self.feed_area)
        hbox.addWidget(self.right_area)

        hbox.setStretchFactor(self.feed_area, 1)
        hbox.setStretchFactor(self.right_area, 3)

        self.setLayout(hbox)

        self.feed_list.itemActivated.connect(self.handle_feed)
        self.article_list.itemActivated.connect(self.handle_article)

        self.feed_object_dict = {}

        self.fetch_feeds()
Esempio n. 30
0
    def create_send_layout(self) -> QVBoxLayout:
        """ Re-render the layout and it's child widgets of this view. """
        # A 4-column grid layout.  All the stretch is in the last column.
        # The exchange rate plugin adds a fiat widget in column 2
        self._send_grid = grid = QGridLayout()
        grid.setSpacing(8)
        # This ensures all columns are stretched over the full width of the last tab.
        grid.setColumnStretch(4, 1)

        self.amount_e = BTCAmountEdit(self)
        self._payto_e = PayToEdit(self)

        # From fields row.
        # This is enabled by "spending" coins in the coins tab.

        self._from_label = QLabel(_('From'), self)
        self._from_label.setContentsMargins(0, 5, 0, 0)
        self._from_label.setAlignment(Qt.AlignTop)
        grid.addWidget(self._from_label, 1, 0)

        self._from_list = MyTreeWidget(self, self._main_window.reference(),
                                       self.from_list_menu,
                                       ['Address / Outpoint', 'Amount'])
        self._from_list.setMaximumHeight(80)
        grid.addWidget(self._from_list, 1, 1, 1, -1)
        self.set_pay_from([])

        msg = (
            _('Recipient of the funds.') + '\n\n' +
            _('You may enter a Bitcoin SV address, a label from your list of '
              'contacts (a list of completions will be proposed), or an alias '
              '(email-like address that forwards to a Bitcoin SV address)'))
        payto_label = HelpLabel(_('Pay to'), msg, self)
        payto_label.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Preferred)
        grid.addWidget(payto_label, 2, 0)
        grid.addWidget(self._payto_e, 2, 1, 1, -1)

        msg = (
            _('Amount to be sent.') + '\n\n' +
            _('The amount will be displayed in red if you do not have '
              'enough funds in your wallet.') + ' ' +
            _('Note that if you have frozen some of your coins, the available '
              'funds will be lower than your total balance.') + '\n\n' +
            _('Keyboard shortcut: type "!" to send all your coins.'))
        amount_label = HelpLabel(_('Amount'), msg, self)
        grid.addWidget(amount_label, 3, 0)
        grid.addWidget(self.amount_e, 3, 1)

        self._fiat_send_e = AmountEdit(
            app_state.fx.get_currency if app_state.fx else '', self)
        self.set_fiat_ccy_enabled(
            bool(app_state.fx and app_state.fx.is_enabled()))

        grid.addWidget(self._fiat_send_e, 3, 2)
        self.amount_e.frozen.connect(
            lambda: self._fiat_send_e.setFrozen(self.amount_e.isReadOnly()))

        self._max_button = EnterButton(_("Max"), self._spend_max, self)
        self._max_button.setSizePolicy(QSizePolicy.Fixed,
                                       QSizePolicy.Preferred)
        grid.addWidget(self._max_button, 3, 3)

        completer = QCompleter()
        completer.setCaseSensitivity(False)
        self._payto_e.set_completer(completer)
        completer.setModel(self._completions)

        msg = (_(
            'Description of the transaction (not mandatory).'
        ) + '\n\n' + _(
            'The description is not sent to the recipient of the funds. '
            'It is stored in your wallet file, and displayed in the \'History\' tab.'
        ))
        description_label = HelpLabel(_('Description'), msg, self)
        grid.addWidget(description_label, 4, 0)
        self._message_e = MyLineEdit(self)
        grid.addWidget(self._message_e, 4, 1, 1, -1)

        self._main_window.connect_fields(self.amount_e, self._fiat_send_e)

        self._coinsplitting_checkbox = QCheckBox(
            _('Add extra data to ensure the coins used '
              'by the transaction are only used on the Bitcoin SV blockchain (coin-splitting).'
              ), self)
        self._coinsplitting_checkbox.setChecked(
            not self._account.involves_hardware_wallet())
        self._coinsplitting_checkbox.setVisible(self._show_splitting_option())
        # Hardware wallets can only sign a small set of fixed types of scripts (not this kind).
        self._coinsplitting_checkbox.setEnabled(
            not self._account.involves_hardware_wallet())

        def coinsplitting_checkbox_cb(state: int) -> None:
            if state != Qt.Checked:
                dialogs.show_named('sv-only-disabled')

        self._coinsplitting_checkbox.stateChanged.connect(
            coinsplitting_checkbox_cb)
        grid.addWidget(self._coinsplitting_checkbox, 5, 1, 1, -1)

        self._help_button = HelpDialogButton(self, "misc", "send-tab",
                                             _("Help"))
        self._preview_button = EnterButton(_("Preview"), self._do_preview,
                                           self)
        self._preview_button.setToolTip(
            _('Display the details of your transactions before signing it.'))
        self._send_button = EnterButton(_("Send"), self._do_send, self)
        if self._main_window.network is None:
            self._send_button.setEnabled(False)
            self._send_button.setToolTip(
                _('You are using ElectrumSV in offline mode; restart '
                  'ElectrumSV if you want to get connected'))
        self._send_button.setVisible(not self._account.is_watching_only())
        self._clear_button = EnterButton(_("Clear"), self.clear, self)

        buttons = QHBoxLayout()
        buttons.addStretch(1)
        buttons.addWidget(self._help_button)
        buttons.addWidget(self._clear_button)
        buttons.addWidget(self._preview_button)
        buttons.addWidget(self._send_button)
        buttons.addStretch(1)
        grid.addLayout(buttons, 7, 0, 1, -1)

        self.amount_e.shortcut.connect(self._spend_max)
        self._payto_e.textChanged.connect(self.update_fee)
        self.amount_e.textEdited.connect(self.update_fee)

        def reset_max(t) -> None:
            # Invoices set the amounts, which invokes this despite them being frozen.
            if self._payment_request is not None:
                return
            self._is_max = False
            self._max_button.setEnabled(not bool(t))

        self.amount_e.textEdited.connect(reset_max)
        self.amount_e.textChanged.connect(self._on_entry_changed)
        self._fiat_send_e.textEdited.connect(reset_max)

        self._invoice_list_toolbar_layout = TableTopButtonLayout()
        self._invoice_list_toolbar_layout.refresh_signal.connect(
            self._main_window.refresh_wallet_display)
        self._invoice_list_toolbar_layout.filter_signal.connect(
            self._filter_invoice_list)

        self._invoice_list = InvoiceList(self, self._main_window.reference())

        vbox0 = QVBoxLayout()
        vbox0.addLayout(grid)
        hbox = QHBoxLayout()
        hbox.addLayout(vbox0)

        invoice_layout = QVBoxLayout()
        invoice_layout.setSpacing(0)
        invoice_layout.setContentsMargins(6, 0, 6, 6)
        invoice_layout.addLayout(self._invoice_list_toolbar_layout)
        invoice_layout.addWidget(self._invoice_list)

        invoice_box = QGroupBox()
        invoice_box.setTitle(_('Invoices'))
        invoice_box.setAlignment(Qt.AlignCenter)
        invoice_box.setContentsMargins(0, 0, 0, 0)
        invoice_box.setLayout(invoice_layout)

        vbox = QVBoxLayout(self)
        vbox.addLayout(hbox)
        vbox.addSpacing(20)
        vbox.addWidget(invoice_box)
        vbox.setStretchFactor(self._invoice_list, 1000)

        return vbox
    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)