Python PyQt4.QtCore() Examples

The following are 20 code examples of PyQt4.QtCore(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module PyQt4 , or try the search function .
Example #1
Source File: pyqt.py    From mgear_core with MIT License 8 votes vote down vote up
def qt_import(shi=False, cui=False):
    """
    import pyside/pyQt

    Returns:
        multi: QtGui, QtCore, QtWidgets, wrapInstance

    """
    lookup = ["PySide2", "PySide", "PyQt4"]

    preferredBinding = os.environ.get("MGEAR_PYTHON_QT_BINDING", None)
    if preferredBinding is not None and preferredBinding in lookup:
        lookup.remove(preferredBinding)
        lookup.insert(0, preferredBinding)

    for binding in lookup:
        try:
            return _qt_import(binding, shi, cui)
        except Exception:
            pass

    raise _qt_import("ThisBindingSurelyDoesNotExist", False, False) 
Example #2
Source File: _compat.py    From mGui with MIT License 6 votes vote down vote up
def _pyside_as_qt_object(widget):
    from PySide.QtCore import QObject
    from PySide.QtGui import QWidget
    from PySide import QtGui
    from shiboken import wrapInstance
    if hasattr(widget, '__qt_object__'):
        return widget.__qt_object__
    ptr = _find_widget_ptr(widget)
    qobject = wrapInstance(long(ptr), QObject)
    meta = qobject.metaObject()
    _class = meta.className()
    _super = meta.superClass().className()
    qclass = getattr(QtGui, _class, getattr(QtGui, _super, QWidget))
    return wrapInstance(long(ptr), qclass) 
Example #3
Source File: _compat.py    From mGui with MIT License 6 votes vote down vote up
def _pyside2_as_qt_object(widget):
    from PySide2.QtCore import QObject
    from PySide2.QtWidgets import QWidget
    from PySide2 import QtWidgets
    from shiboken2 import wrapInstance
    if hasattr(widget, '__qt_object__'):
        return widget.__qt_object__
    ptr = _find_widget_ptr(widget)
    qobject = wrapInstance(long(ptr), QObject)
    meta = qobject.metaObject()
    _class = meta.className()
    _super = meta.superClass().className()
    qclass = getattr(QtWidgets, _class, getattr(QtWidgets, _super, QWidget))
    return wrapInstance(long(ptr), qclass) 
Example #4
Source File: pyqt.py    From mgear_core with MIT License 6 votes vote down vote up
def _qt_import(binding, shi=False, cui=False):
    QtGui = None
    QtCore = None
    QtWidgets = None
    wrapInstance = None

    if binding == "PySide2":
        from PySide2 import QtGui, QtCore, QtWidgets
        import shiboken2 as shiboken
        from shiboken2 import wrapInstance
        from pyside2uic import compileUi

    elif binding == "PySide":
        from PySide import QtGui, QtCore
        import PySide.QtGui as QtWidgets
        import shiboken
        from shiboken import wrapInstance
        from pysideuic import compileUi

    elif binding == "PyQt4":
        from PyQt4 import QtGui
        from PyQt4 import QtCore
        import PyQt4.QtGui as QtWidgets
        from sip import wrapinstance as wrapInstance
        from PyQt4.uic import compileUi
        print("Warning: 'shiboken' is not supported in 'PyQt4' Qt binding")
        shiboken = None

    else:
        raise Exception("Unsupported python Qt binding '%s'" % binding)

    rv = [QtGui, QtCore, QtWidgets, wrapInstance]
    if shi:
        rv.append(shiboken)
    if cui:
        rv.append(compileUi)
    return rv 
Example #5
Source File: qtconsole.py    From pyweed with GNU Lesser General Public License v3.0 5 votes vote down vote up
def new_load_qt(api):
    """
    Directly import the Qt libraries rather than autodiscovering them
    """
    from PyQt4 import QtCore, QtGui, QtSvg
    return QtCore, QtGui, QtSvg, 'pyqt' 
Example #6
Source File: qt.py    From artview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_matplotlib_qt_backend():
    print ("testing matplotlib qt backend ...")
    try:
        # Matplot changed its file structure several times in history, so we
        # must test all
        try:
            from matplotlib.backends.qt_compat import QtCore
        except:
            try:
                from matplotlib.backends.qt4_compat import QtCore
            except:
                from matplotlib.backends.qt import QtCore
        from PyQt4 import QtCore as QtCore4

        if QtCore is QtCore4:
            print ("... test passed")
            return True
        else:
            using = QtCore.__name__.split('.')[0]
            expect = QtCore4.__name__.split('.')[0]
            print ("... Qt test FAILURE\n" +
                   "    Matplotlib is using %s\n" % using +
                   "    It must use %s\n" % expect +
                   "    Possible reasons for that are that " +
                   "%s is not installed " % expect +
                   "or the envoriment variable QT_API is overwriting it.")
            return False
    except:
        import traceback
        print(traceback.format_exc())
        print ("... If you experience this test failure, it may be an "
               "expected! We would like to know why, "
               "please report in 'https://github.com/nguy/artview/issues'")
        return None 
Example #7
Source File: qt.py    From xrt with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(QComboBox, self).__init__(*args, **kwargs)
#        self.scrollWidget=scrollWidget
        self.setFocusPolicy(QtCore.Qt.StrongFocus) 
Example #8
Source File: main_window.py    From encompass with GNU General Public License v3.0 5 votes vote down vote up
def change_currency_dialog(self):
        import operator
        d = QDialog(self)
        d.setWindowTitle(_('Change Currency'))
        main_layout = QVBoxLayout()
        change_info = QLabel( _("Note that you will need to enter your password the first time you use a new currency.\n") )
        change_info.setWordWrap(True)
        main_layout.addWidget(change_info)

        key_info = QLabel( _("PoW: Whether this wallet verifies proof-of-work.\nServers: Number of default servers to get data from.") )
        key_info.setWordWrap(True)
        main_layout.addWidget(key_info)

        chains_view = QTreeWidget()
        chains_view.setColumnCount(4)
        chains_view.setHeaderLabels([ _('Code'), _('Currency'), _('PoW'), _('Servers') ])
        chains_view.setColumnWidth(0, 75)
        chains_view.setColumnWidth(1, 125)
        chains_view.setColumnWidth(2, 60)
        chains_view.setColumnWidth(3, 50)
        chains_view.setMinimumWidth(325)
        chains = chainkey.chainparams._known_chains
        # Yes or No
        y_or_n = lambda x: 'Yes' if x==True else 'No'
        for ch in sorted(chains, key=operator.attrgetter('code')):
            server_trust = chainkey.chainparams.get_server_trust(ch.code)
            uses_pow = server_trust['pow']
            num_servers = server_trust['servers']
            item = QTreeWidgetItem([ch.code, ch.coin_name, y_or_n(uses_pow), str(num_servers)])
            chains_view.addTopLevelItem(item)
        chains_view.setCurrentItem(chains_view.topLevelItem(0))
        main_layout.addWidget(chains_view)

        main_layout.addLayout(ok_cancel_buttons(d))
        d.setLayout(main_layout)

        if not d.exec_(): return
        chaincode = str(chains_view.currentItem().text(0))
        self.emit(QtCore.SIGNAL('change_currency'), chaincode) 
Example #9
Source File: main_window.py    From encompass with GNU General Public License v3.0 5 votes vote down vote up
def connect_slots(self, sender):
        self.connect(sender, QtCore.SIGNAL('timersignal'), self.timer_actions)
        self.previous_payto_e='' 
Example #10
Source File: main_window.py    From encompass with GNU General Public License v3.0 5 votes vote down vote up
def keyPressEvent(self, e):
        if e.key() == QtCore.Qt.Key_Return:
            apply(self.func,()) 
Example #11
Source File: __init__.py    From encompass with GNU General Public License v3.0 5 votes vote down vote up
def eventFilter(self, obj, event):
        if event.type() == QtCore.QEvent.FileOpen:
            if len(self.windows) >= 1:
                self.windows[0].set_url(event.url().toEncoded())
                return True
        return False 
Example #12
Source File: assert_modules.py    From ibeis with Apache License 2.0 5 votes vote down vote up
def PyQt4_version():
    # FIXME, pyqt5 is also ok
    from PyQt4 import QtCore
    return module_stdinfo_dict(QtCore, 'PYQT_VERSION_STR') 
Example #13
Source File: __init__.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def load_stylesheet_pyqt5():
    """
    Load the stylesheet for use in a pyqt5 application.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    warnings.warn(
        "load_stylesheet_pyqt5() will be deprecated in version 3,"
        "set QtPy environment variable to specify the Qt binding and "
        "use load_stylesheet()",
        PendingDeprecationWarning
    )
    # Smart import of the rc file
    import qdarkstyle.pyqt5_style_rc

    # Load the stylesheet content from resources
    from PyQt5.QtCore import QFile, QTextStream

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #31363b;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet 
Example #14
Source File: ui_main.py    From Python-GUI-examples with MIT License 5 votes vote down vote up
def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(993, 692)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.horizontalLayout = QtGui.QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.pbLevel = QtGui.QProgressBar(self.centralwidget)
        self.pbLevel.setMaximum(1000)
        self.pbLevel.setProperty("value", 123)
        self.pbLevel.setTextVisible(False)
        self.pbLevel.setOrientation(QtCore.Qt.Vertical)
        self.pbLevel.setObjectName(_fromUtf8("pbLevel"))
        self.horizontalLayout.addWidget(self.pbLevel)
        self.frame = QtGui.QFrame(self.centralwidget)
        self.frame.setFrameShape(QtGui.QFrame.NoFrame)
        self.frame.setFrameShadow(QtGui.QFrame.Plain)
        self.frame.setObjectName(_fromUtf8("frame"))
        self.verticalLayout = QtGui.QVBoxLayout(self.frame)
        self.verticalLayout.setMargin(0)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.label = QtGui.QLabel(self.frame)
        self.label.setObjectName(_fromUtf8("label"))
        self.verticalLayout.addWidget(self.label)
        self.grFFT = PlotWidget(self.frame)
        self.grFFT.setObjectName(_fromUtf8("grFFT"))
        self.verticalLayout.addWidget(self.grFFT)
        self.label_2 = QtGui.QLabel(self.frame)
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.verticalLayout.addWidget(self.label_2)
        self.grPCM = PlotWidget(self.frame)
        self.grPCM.setObjectName(_fromUtf8("grPCM"))
        self.verticalLayout.addWidget(self.grPCM)
        self.horizontalLayout.addWidget(self.frame)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow) 
Example #15
Source File: __init__.py    From vnpy_crypto with MIT License 4 votes vote down vote up
def load_stylesheet(pyside=True):
    """
    Load the stylesheet. Takes care of importing the rc module.

    :param pyside: True to load the pyside rc file, False to load the PyQt rc file

    :return the stylesheet string
    """
    warnings.warn(
        "load_stylesheet() will not receive pyside parameter in version 3. "
        "Set QtPy environment variable to specify the Qt binding insteady.",
        FutureWarning
    )
    # Smart import of the rc file
    if pyside:
        import qdarkstyle.pyside_style_rc
    else:
        import qdarkstyle.pyqt_style_rc

    # Load the stylesheet content from resources
    if not pyside:
        from PyQt4.QtCore import QFile, QTextStream
    else:
        from PySide.QtCore import QFile, QTextStream

    f = QFile(":qdarkstyle/style.qss")
    if not f.exists():
        _logger().error("Unable to load stylesheet, file not found in "
                        "resources")
        return ""
    else:
        f.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(f)
        stylesheet = ts.readAll()
        if platform.system().lower() == 'darwin':  # see issue #12 on github
            mac_fix = '''
            QDockWidget::title
            {
                background-color: #31363b;
                text-align: center;
                height: 12px;
            }
            '''
            stylesheet += mac_fix
        return stylesheet 
Example #16
Source File: binding_helper.py    From calfem-python with MIT License 4 votes vote down vote up
def _load_pyqt(required_modules, optional_modules):
    # set environment variable QT_API for matplotlib
    os.environ['QT_API'] = 'pyqt'

    # select PyQt4 API, see http://pyqt.sourceforge.net/Docs/PyQt4/incompatible_apis.html
    import sip
    try:
        sip.setapi('QDate', 2)
        sip.setapi('QDateTime', 2)
        sip.setapi('QString', 2)
        sip.setapi('QTextStream', 2)
        sip.setapi('QTime', 2)
        sip.setapi('QUrl', 2)
        sip.setapi('QVariant', 2)
    except ValueError as e:
        raise RuntimeError('Could not set API version (%s): did you import PyQt4 directly?' % e)

    # register required and optional PyQt4 modules
    for module_name in required_modules:
        _named_import('PyQt4.%s' % module_name)
    for module_name in optional_modules:
        _named_optional_import('PyQt4.%s' % module_name)

    # set some names for compatibility with PySide
    sys.modules['QtCore'].Signal = sys.modules['QtCore'].pyqtSignal
    sys.modules['QtCore'].Slot = sys.modules['QtCore'].pyqtSlot
    sys.modules['QtCore'].Property = sys.modules['QtCore'].pyqtProperty

    # try to register PyQt4.Qwt5 module
    try:
        import PyQt4.Qwt5
        _register_binding_module('Qwt', PyQt4.Qwt5)
    except ImportError:
        pass

    global _loadUi

    def _loadUi(uifile, baseinstance=None, custom_widgets_=None):
        from PyQt4 import uic
        return uic.loadUi(uifile, baseinstance=baseinstance)

    # override specific function to improve compatibility between different bindings
    from QtGui import QFileDialog
    QFileDialog.getOpenFileName = QFileDialog.getOpenFileNameAndFilter
    QFileDialog.getSaveFileName = QFileDialog.getSaveFileNameAndFilter

    import PyQt4.QtCore
    return PyQt4.QtCore.PYQT_VERSION_STR 
Example #17
Source File: binding_helper.py    From calfem-python with MIT License 4 votes vote down vote up
def _select_qt_binding(binding_name=None, binding_order=None):
    global QT_BINDING, QT_BINDING_VERSION

    # order of default bindings can be changed here
    DEFAULT_BINDING_ORDER = ['pyqt', 'pyside']
    binding_order = binding_order or DEFAULT_BINDING_ORDER

    # determine binding preference
    if binding_name:
        if binding_name not in binding_order:
            raise ImportError("Qt binding '%s' is unknown" % binding_name)
        binding_order = [binding_name]

    required_modules = [
        'QtCore',
        'QtGui',
        'uic',
    ]
    optional_modules = [
        'QtDeclarative',
        'QtMultimedia',
        'QtNetwork',
        'QtOpenGL',
        'QtOpenVG',
        'QtScript',
        'QtScriptTools'
        'QtSql',
        'QtSvg',
        'QtWebKit',
        'QtXml',
        'QtXmlPatterns',
        'QtUiTools',
    ]

    # try to load preferred bindings
    error_msgs = []
    for binding_name in binding_order:
        try:
            binding_loader = getattr(sys.modules[__name__], '_load_%s' % binding_name, None)
            if binding_loader:
                QT_BINDING_VERSION = binding_loader(required_modules, optional_modules)
                QT_BINDING = binding_name
                break
            else:
                error_msgs.append("  Binding loader '_load_%s' not found." % binding_name)
        except ImportError as e:
            error_msgs.append("  ImportError for '%s': %s" % (binding_name, e))

    if not QT_BINDING:
        raise ImportError("Could not find Qt binding (looked for: %s):\n%s" % (', '.join(["'%s'" % b for b in binding_order]), '\n'.join(error_msgs))) 
Example #18
Source File: binding_helper.py    From compoundpi with GNU General Public License v2.0 4 votes vote down vote up
def _select_qt_binding(binding_name=None, binding_order=None):
    global QT_BINDING, QT_BINDING_VERSION

    # order of default bindings can be changed here
    DEFAULT_BINDING_ORDER = ['pyqt', 'pyside']
    binding_order = binding_order or DEFAULT_BINDING_ORDER

    # determine binding preference
    if binding_name:
        if binding_name not in binding_order:
            raise ImportError("Qt binding '%s' is unknown" % binding_name)
        binding_order = [binding_name]

    required_modules = [
        'QtCore',
        'QtGui'
    ]
    optional_modules = [
        'QtDeclarative',
        'QtMultimedia',
        'QtNetwork',
        'QtOpenGL',
        'QtOpenVG',
        'QtScript',
        'QtScriptTools'
        'QtSql',
        'QtSvg',
        'QtWebKit',
        'QtXml',
        'QtXmlPatterns',
    ]

    # try to load preferred bindings
    error_msgs = []
    for binding_name in binding_order:
        try:
            binding_loader = globals().get('_load_%s' % binding_name, None)
            if binding_loader:
                QT_BINDING_VERSION = binding_loader(
                        required_modules, optional_modules)
                QT_BINDING = binding_name
                break
            else:
                error_msgs.append(
                        "  Binding loader '_load_%s' not found." % binding_name)
        except ImportError as e:
            error_msgs.append(
                    "  ImportError for '%s': %s" % (binding_name, e))

    if not QT_BINDING:
        raise ImportError(
                "Could not find Qt binding (looked for: %s):\n%s" % (
                    ', '.join(["'%s'" % b for b in binding_order]),
                    '\n'.join(error_msgs))
                ) 
Example #19
Source File: binding_helper.py    From compoundpi with GNU General Public License v2.0 4 votes vote down vote up
def _load_pyqt(required_modules, optional_modules):
    os.environ['QT_API'] = 'pyqt'

    # select PyQt4 API, see
    # http://pyqt.sourceforge.net/Docs/PyQt4/incompatible_apis.html
    import sip
    try:
        sip.setapi('QDate', 2)
        sip.setapi('QDateTime', 2)
        sip.setapi('QString', 2)
        sip.setapi('QTextStream', 2)
        sip.setapi('QTime', 2)
        sip.setapi('QUrl', 2)
        sip.setapi('QVariant', 2)
    except ValueError as e:
        raise RuntimeError(
                'Could not set API version (%s): did you import PyQt4 '
                'directly?' % e)

    for module_name in required_modules:
        _named_import('PyQt4.%s' % module_name)
    for module_name in optional_modules:
        _named_optional_import('PyQt4.%s' % module_name)

    # set some names for compatibility with PySide
    sys.modules['PyQt4.QtCore'].Signal   = sys.modules['PyQt4.QtCore'].pyqtSignal
    sys.modules['PyQt4.QtCore'].Slot     = sys.modules['PyQt4.QtCore'].pyqtSlot
    sys.modules['PyQt4.QtCore'].Property = sys.modules['PyQt4.QtCore'].pyqtProperty

    try:
        import PyQt4.Qwt5
        _register_binding_module('Qwt', PyQt4.Qwt5)
    except ImportError:
        pass

    global _loadUi

    def _loadUi(uifile, baseinstance=None, custom_widgets_=None):
        from PyQt4 import uic
        return uic.loadUi(uifile, baseinstance=baseinstance)

    # override specific function to improve compatibility between different
    # bindings
    from PyQt4.QtGui import QFileDialog
    QFileDialog.getOpenFileName = QFileDialog.getOpenFileNameAndFilter
    QFileDialog.getSaveFileName = QFileDialog.getSaveFileNameAndFilter

    import PyQt4.QtCore
    return PyQt4.QtCore.PYQT_VERSION_STR 
Example #20
Source File: pybarcode.py    From viivakoodi with MIT License 4 votes vote down vote up
def main():
    msg = []
    if ImageWriter is None:
        msg.append('Image output disabled (PIL not found), --type option '
                   'disabled.')
    else:
        msg.append('Image output enabled, use --type option to give image '
                   'format (png, jpeg, ...).')
    if QtCore is None:
        msg.append('PyQt not found, gui action disabled.')
    else:
        msg.append('PyQt found. Use gui action to get a simple GUI.')
    parser = ArgumentParser(
        description=barcode.__description__,
        epilog=' '.join(msg))
    parser.add_argument(
        '-v', '--version',
        action='version',
        version='%(prog)s ' + barcode.__release__)
    subparsers = parser.add_subparsers(title='Actions')
    create_parser = subparsers.add_parser(
        'create',
        help='Create a barcode with the given options.')
    create_parser.add_argument(
        'code',
        help='Code to render as barcode.')
    create_parser.add_argument(
        'output',
        help='Filename for output without extension, e.g. mybarcode.')
    create_parser.add_argument(
        '-c', '--compress',
        action='store_true',
        help='Compress output, only recognized if type is svg.')
    create_parser.add_argument(
        '-b', '--barcode',
        help='Barcode to use [default: %(default)s].')
    if ImageWriter is not None:
        create_parser.add_argument(
            '-t', '--type',
            help='Type of output [default: %(default)s].')
    list_parser = subparsers.add_parser(
        'list', help='List available image and code types.')
    list_parser.set_defaults(func=list_types)
    if QtCore is not None:
        gui_parser = subparsers.add_parser(
            'gui', help='Opens a simple PyQt GUI to create barcodes.')
        gui_parser.set_defaults(func=open_gui)
    create_parser.set_defaults(
        barcode='code39',
        compress=False,
        func=create_barcode,
        type='svg')
    args = parser.parse_args()
    args.func(args, parser)