Пример #1
0
    def test_add_action_different_context(self):
        """
        ActionList test - Tests the add_action method. The actions have the different parent, the same shortcuts and
        both have the QtCore.Qt.WidgetShortcut shortcut context set.
        """
        # GIVEN: Two actions with the same shortcuts.
        parent = QtCore.QObject()
        action3 = QtWidgets.QAction(parent)
        action3.setObjectName('action3')
        action3.setShortcutContext(QtCore.Qt.WidgetShortcut)
        second_parent = QtCore.QObject()
        action_with_same_shortcuts3 = QtWidgets.QAction(second_parent)
        action_with_same_shortcuts3.setObjectName('action_with_same_shortcuts3')
        action_with_same_shortcuts3.setShortcutContext(QtCore.Qt.WidgetShortcut)
        # Add default shortcuts to Settings class.
        default_shortcuts = {
            'shortcuts/action3': [QtGui.QKeySequence(QtCore.Qt.Key_E), QtGui.QKeySequence(QtCore.Qt.Key_F)],
            'shortcuts/action_with_same_shortcuts3': [QtGui.QKeySequence(QtCore.Qt.Key_E),
                                                      QtGui.QKeySequence(QtCore.Qt.Key_F)]
        }
        Settings.extend_default_settings(default_shortcuts)

        # WHEN: Add the two actions to the action list.
        self.action_list.add_action(action3, 'example_category2')
        self.action_list.add_action(action_with_same_shortcuts3, 'example_category2')
        # Remove the actions again.
        self.action_list.remove_action(action3, 'example_category2')
        self.action_list.remove_action(action_with_same_shortcuts3, 'example_category2')

        # THEN: Both action should keep their shortcuts.
        assert len(action3.shortcuts()) == 2, 'The action should have two shortcut assigned.'
        assert len(action_with_same_shortcuts3.shortcuts()) == 2, 'The action should have two shortcuts assigned.'
Пример #2
0
    def test_add_action_different_parent(self):
        """
        ActionList test - Tests the add_action method. The actions have the different parent, the same shortcuts and
        both have the QtCore.Qt.WindowShortcut shortcut context set.
        """
        # GIVEN: Two actions with the same shortcuts.
        parent = QtCore.QObject()
        action2 = QtWidgets.QAction(parent)
        action2.setObjectName('action2')
        second_parent = QtCore.QObject()
        action_with_same_shortcuts2 = QtWidgets.QAction(second_parent)
        action_with_same_shortcuts2.setObjectName('action_with_same_shortcuts2')
        # Add default shortcuts to Settings class.
        default_shortcuts = {
            'shortcuts/action2': [QtGui.QKeySequence(QtCore.Qt.Key_C), QtGui.QKeySequence(QtCore.Qt.Key_D)],
            'shortcuts/action_with_same_shortcuts2': [QtGui.QKeySequence(QtCore.Qt.Key_D),
                                                      QtGui.QKeySequence(QtCore.Qt.Key_C)]
        }
        Settings.extend_default_settings(default_shortcuts)

        # WHEN: Add the two actions to the action list.
        self.action_list.add_action(action2, 'example_category')
        self.action_list.add_action(action_with_same_shortcuts2, 'example_category')
        # Remove the actions again.
        self.action_list.remove_action(action2, 'example_category')
        self.action_list.remove_action(action_with_same_shortcuts2, 'example_category')

        # THEN: As both actions have the same shortcuts, they should be removed from one action.
        assert len(action2.shortcuts()) == 2, 'The action should have two shortcut assigned.'
        assert len(action_with_same_shortcuts2.shortcuts()) == 0, 'The action should not have a shortcut assigned.'
    def init(self, _acl_xml: str = None) -> None:
        """
        Read the file "acl.xml" and establish a new access control list.

        If the file "acl.xml" cannot be read, the access control list is empty and
        no access control will be processed on any object.

        @param _acl_xml XML content with the definition of the access control list.
        """
        if _acl_xml is None:

            if application.PROJECT.conn_manager is None:
                raise Exception("Project is not connected yet")

            _acl_xml = application.PROJECT.conn_manager.managerModules(
            ).content("acl.xml")

        doc = QtXml.QDomDocument("ACL")
        if self._access_control_list:
            self._access_control_list.clear()

        if _acl_xml and not doc.setContent(_acl_xml):
            LOGGER.warning(
                QtCore.QObject().tr("Lista de control de acceso errónea"))
            return

        self._access_control_list = {}
        # self._access_control_list.setAutoDelete(True)

        doc_elem = doc.documentElement()
        node = doc_elem.firstChild()

        if node.isNull():
            return

        while not node.isNull():
            element = node.toElement()
            if element:
                if element.tagName() == "name":
                    self._name = element.text()
                    node = node.nextSibling()
                    continue

                rule = pnaccesscontrolfactory.PNAccessControlFactory().create(
                    element.tagName())
                if rule:
                    rule.set(element)
                    self._access_control_list["%s::%s::%s" %
                                              (rule.type(), rule.name(),
                                               rule.user())] = rule
                    node = node.nextSibling()
                    continue

            node = node.nextSibling()

        LOGGER.warning(
            QtCore.QObject().tr("Lista de control de acceso cargada"))
Пример #4
0
    def __init__(self, module: str, *args: Any, **kwargs: Any):
        super(WidgetHandler, self).__init__(*args, **kwargs)
        self.module = module
        config = conf.serverConfig["modules"][module]
        if config["icon"]:
            if config["icon"].lower().startswith("http://") or config[
                    "icon"].lower().startswith("https://"):
                icon = config["icon"]
            else:
                icon = loadIcon(config["icon"])
        else:
            icon = loadIcon("hierarchy")
        super(HierarchyCoreHandler,
              self).__init__(lambda: HierarchyWidget(module),
                             sortIndex=config.get("sortIndex", 0),
                             descr=config["name"],
                             icon=icon,
                             vanishOnClose=False,
                             *args,
                             **kwargs)

        self.repos: List[Dict[str, Any]] = list()
        self.tmp_obj = QtCore.QObject()
        fetchTask = NetworkService.request("/%s/listRootNodes" % module,
                                           parent=self.tmp_obj)
        fetchTask.requestSucceeded.connect(self.setRepos)
Пример #5
0
    def __init__(self, parent, x, y, w, h, item):
        self.cmptEmitter = QtCore.QObject()
        iParent = item
        '''
        self._rect = QtCore.QRectF(x,y,w,h)
        self._scene = parent
        print "self comptItem",self._scene.sceneContainer ," and",self._scene.sceneContainer.graphicsView
        self.mouseOver = False
        self.resizeHandleSize = 4.0
        self.mousePressPos = None
        self.mouseMovePos = None
        self.mouseIsPressed = False
        #self.setAcceptsHoverEvents(True)
        self.updateResizeHandles()
        '''
        if hasattr(iParent, "__iter__"):
            self.mobj = iParent[0]
        else:
            self.mobj = iParent
        self.layoutWidgetPt = parent
        QGraphicsRectItem.__init__(self, x, y, w, h)

        self.setFlag(QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QGraphicsItem.ItemIsSelectable)
        #self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, 1)
        QT_VERSION = str(QtCore.QT_VERSION_STR).split('.')
        QT_MINOR_VERSION = int(QT_VERSION[1])
        if QT_MINOR_VERSION >= 6:
            #if config.QT_MINOR_VERSION >= 6:
            self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, 1)
        self.setAcceptHoverEvents(True)
        self.setToolTip(iParent.name)
Пример #6
0
    def __init__(self, fname=None):
        if not isinstance(fname, str):
            fname = defaultLogFileName
        self.fname = fname
        self.create_file()

        self.msg_list = []

        self.err_flag = False
        self.signalemitter = QtCore.QObject()

        # TODO Read This from Config
        self.dbg_verbosity_level = 5
        # self.logtime = myConfig.get_boolean("Logging","log_showTime")

        self.t_zero = time.time()
        #         self.message(" ------ Logging started: %s -----" % time.ctime() )

        # hardcoded logging values for the time before existance of myConfig
        # instance
        self.show_error = True
        self.show_warning = True
        self.show_debug = True

        # The terminal on the GUI into which the messages are written. Will be set later.
        self.ppTerminal = None
Пример #7
0
    def sql_listener(self, query, check_query=True):
        """
        :param str query:
        :param bool check_query:
        """
        self.query = query.strip()
        if check_query and self._last_query.lower() == self.query.lower():
            message = 'Your last query was the same. ' \
                      'Do you want to make this query again?'
            signals.show_yes_no_dialog.emit(message, self.query)
            return
        signals.show_status.emit(f'Processing.... {self.query}')
        try:
            response = self.cursor.execute(self.query)
            if self.cursor.description:
                headers = [item[0] for item in self.cursor.description]
                # Send headers
                signals.headers_received.emit(headers)

            self.query_processing = QueryThread(response)

            local_object = QtCore.QObject()
            local_object.moveToThread(self.query_processing)
            self.query_processing.finished.connect(self.request_done)
            self.query_processing.start()
        except Exception as err:
            signals.error_received.emit(f'Error: {err}')
            self.request_done()
Пример #8
0
    def renderReport(self,
                     init_row: int = 0,
                     init_col: int = 0,
                     flags: List[int] = [],
                     pages: Any = None) -> "QtCore.QObject":
        """Render report."""
        if self.rd and self.rt and self.rt.find("KugarTemplate") > -1:
            data = self.rd.toString(1)
            self.report_ = self.parser_.parse(self.d_.template_, self.rt, data,
                                              self.report_, flags)

        return QtCore.QObject()  # return self.pages!
Пример #9
0
    def __init__(self,
                 viewport,
                 viewportMngr,
                 vpType,
                 prototypeMngr,
                 parent=None):
        """ Initialization of the CompositionView class
            
        Parameters:
            viewportMngr - the manager of the viewports where the composition
                           view can reside in
            prototypeMngr - the manager of the prototypes is used to obtain
                            the results of the solver
        """
        QtWidgets.QDialog.__init__(self, parent)
        self.prototypeManager = prototypeMngr
        self.viewport = viewport
        self.viewportManager = viewportMngr
        self.settings = Settings()
        self.setWindowFlags(QtCore.Qt.Window)
        self.timer = QtCore.QObject()
        # QtCore.qsrand(QtCore.QTime(0,0,0).secsTo(QtCore.QTime.currentTime()))

        self.tree = Tree(None)
        self.infoOverlay = CVInfoOverlay(self)
        self.connections = []
        self.ui = Ui_compositionView()
        self.ui.setupUi(self)
        self.ui.graphicsView.setupViewport(
            QtOpenGL.QGLWidget(
                QtOpenGL.QGLFormat(QtOpenGL.QGL.SampleBuffers
                                   | QtOpenGL.QGL.DoubleBuffer)))
        # self.ui.graphicsView.setViewport(QtGui.QWidget())
        self.ui.graphicsView.setRenderHints(
            QtGui.QPainter.Antialiasing | QtGui.QPainter.SmoothPixmapTransform)

        self.collapsed = False
        self.currentTool = None
        self.viewportType = vpType
        self.first = False
        self.nodeId = 0

        self.overConstrainedColor = QtGui.QColor(0, 0, 255)
        self.underConstrainedColor = QtGui.QColor(255, 0, 0)
        self.wellConstrainedColor = QtGui.QColor(0, 255, 0)
        self.unsolvedColor = QtGui.QColor(125, 124, 255)

        self.setScene()
        self.createTriggers()
Пример #10
0
def main():
    app = QtWidgets.QApplication(sys.argv)
    app.setFont(QtGui.QFont("Ubuntu Mono"))
    engine = QtQml.QQmlApplicationEngine()
    interfaces = Interfaces()
    engine.rootContext().setContextProperty('interfaces', interfaces)
    sniffer = Sniffer()
    engine.rootContext().setContextProperty('sniffer', sniffer)

    packetItemModel = sniffer.packetItemModel
    engine.rootContext().setContextProperty('packetItemModel', packetItemModel)
    engine.load(QUrl('main.qml'))

    topLevel = QtCore.QObject()
    topLevel = engine.rootObjects()[0]

    window = QtQuick.QQuickWindow()
    window = topLevel

    window.show()
    sys.exit(app.exec_())
Пример #11
0
 def mainForm(self) -> Any:
     """Return mainForm."""
     return QtCore.QObject()
Пример #12
0
def test_updater_add_watch_raises_error_on_watch_without_signal_finished(
        application):
    with pytest.raises(AttributeError):
        updater.UpdaterProgressDialog(None).addWatch(QtCore.QObject())
Пример #13
0
import typing

from PyQt5 import QtCore
from PyQt5 import QtWidgets

q = QtCore.QObject()

a = q.findChildren(QtCore.QObject)  # type: typing.List[QtCore.QObject]
b = q.findChildren(QtWidgets.QWidget)  # type: typing.List[QtWidgets.QWidget]
c = q.findChildren((QtCore.QObject, ))  # type: typing.List[QtCore.QObject]
d = q.findChildren((QtWidgets.QWidget, ))  # type: typing.List[QtCore.QObject]
# desired error
# Incompatible types in assignment (expression has type "List[QObject]", variable has type "List[QWidget]")
# e = q.findChildren((QtWidgets.QWidget,))  # type: typing.List[QtWidgets.QWidget]