def _pyqt5():
import PyQt5.Qt
# Remap
PyQt5.QtCore.Signal = PyQt5.QtCore.pyqtSignal
PyQt5.QtCore.Slot = PyQt5.QtCore.pyqtSlot
PyQt5.QtCore.Property = PyQt5.QtCore.pyqtProperty
# Add
PyQt5.__wrapper_version__ = __version__
PyQt5.__binding__ = "PyQt5"
PyQt5.__binding_version__ = PyQt5.QtCore.PYQT_VERSION_STR
PyQt5.__qt_version__ = PyQt5.QtCore.QT_VERSION_STR
PyQt5.load_ui = pyqt5_load_ui
return PyQt5
python类Qt()的实例源码
def pyside_load_ui(fname):
"""Read Qt Designer .ui `fname`
Args:
fname (str): Absolute path to .ui file
Usage:
>> from Qt import load_ui
>> class MyWindow(QtWidgets.QWidget):
.. fname = 'my_ui.ui'
.. self.ui = load_ui(fname)
..
>> window = MyWindow()
"""
from PySide import QtUiTools
return QtUiTools.QUiLoader().load(fname)
def __init__(self, parent=None):
QtWidgets.QFrame.__init__(self, parent)
# No title bar, but keep the frame
# self.setWindowFlags(QtCore.Qt.CustomizeWindowHint)
# Set position of the frame
self.screen = QtWidgets.QDesktopWidget().screenGeometry()
# Set geometry
self.setGeometry(self.screen.width()/8, 50, 1600, 900)
self.setMinimumSize(0, 0)
# Set Widgets
self.sideWindow = SideFrame(self)
self.mainWindow = MainFrame(self)
# Set Layout
self.appLayout = QtWidgets.QHBoxLayout()
self.appLayout.addWidget(self.sideWindow, 2)
self.appLayout.addWidget(self.mainWindow, 8)
# Add layout
self.appLayout.setContentsMargins(0, 0, 0, 0)
self.appLayout.setSpacing(0)
self.setLayout(self.appLayout)
self.setWindowTitle("Bayesian Adaptive Trial Simulator")
# Close the application
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
# Layout
self.runmenulayout = QtWidgets.QVBoxLayout()
# Widget
self.runmenuLabel = QtWidgets.QLabel()
self.runmenuLabel.setText("Task is running\nPlease wait...")
# self.runmenuMovieLabel = QtWidgets.QLabel()
# self.runmenuMovie = QtGui.QMovie(":/resources/runmenu.gif")
# self.runmenuMovieLabel.setMovie(self.runmenuMovie)
# self.runmenuMovieLabel.show()
# Add Widget
self.runmenulayout.addWidget(self.runmenuLabel)
# self.runmenulayout.addWidget(self.runmenuMovieLabel)
# Set layout
self.runmenulayout.setAlignment(QtCore.Qt.AlignCenter)
self.runmenulayout.setSpacing(0)
self.runmenulayout.setContentsMargins(10, 0, 10, 0)
self.setLayout(self.runmenulayout)
# Stylesheet
self.setStyleSheet("QLabel{background:transparent; color:#3d5159; font-family:'Segoe UI'; font-size:13pt; border:none;}")
def __init__(self, parent=None):
super().__init__(parent)
# These are set by Qt Designer
self.text_preview = None
self.graphics_preview = None
def _pyqt4():
# Attempt to set sip API v2 (must be done prior to importing PyQt4)
import sip
try:
sip.setapi("QString", 2)
sip.setapi("QVariant", 2)
sip.setapi("QDate", 2)
sip.setapi("QDateTime", 2)
sip.setapi("QTextStream", 2)
sip.setapi("QTime", 2)
sip.setapi("QUrl", 2)
except AttributeError:
raise ImportError
# PyQt4 < v4.6
except ValueError:
# API version already set to v1
raise ImportError
import PyQt4.Qt
# Remap
PyQt4.QtWidgets = PyQt4.QtGui
PyQt4.QtCore.Signal = PyQt4.QtCore.pyqtSignal
PyQt4.QtCore.Slot = PyQt4.QtCore.pyqtSlot
PyQt4.QtCore.Property = PyQt4.QtCore.pyqtProperty
PyQt4.QtCore.QItemSelection = PyQt4.QtGui.QItemSelection
PyQt4.QtCore.QItemSelectionModel = PyQt4.QtGui.QItemSelectionModel
# Add
PyQt4.__wrapper_version__ = __version__
PyQt4.__binding__ = "PyQt4"
PyQt4.__binding_version__ = PyQt4.QtCore.PYQT_VERSION_STR
PyQt4.__qt_version__ = PyQt4.QtCore.QT_VERSION_STR
PyQt4.load_ui = pyqt4_load_ui
return PyQt4
def pyside2_load_ui(fname):
"""Read Qt Designer .ui `fname`
Args:
fname (str): Absolute path to .ui file
"""
from PySide2 import QtUiTools
return QtUiTools.QUiLoader().load(fname)
def pyqt4_load_ui(fname):
"""Read Qt Designer .ui `fname`
Args:
fname (str): Absolute path to .ui file
"""
from PyQt4 import uic
return uic.loadUi(fname)
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
# Add new font
self.titleFont = QtGui.QFont('Caviar Dreams', 20)
self.titleFont.setLetterSpacing(QtGui.QFont.AbsoluteSpacing, 2.0)
# Parent widget, application window
self.parent = parent
# Mouse
self.clickPos = QtCore.QPoint(50, 50)
# Layout
self.titleLayout = QtWidgets.QHBoxLayout()
# Icon
self.iconLabel = QtWidgets.QLabel()
self.iconLabel.setPixmap(QtGui.QPixmap(":/resources/bcts.png").scaled(QtCore.QSize(100, 100)))
self.iconLabel.setAlignment(QtCore.Qt.AlignCenter)
# Title text
self.titleLabel = QtWidgets.QLabel("BATS")
self.titleLabel.setFont(self.titleFont)
# Stylesheet
self.setStyleSheet("QLabel{color:#ffffff;}")
# Add widget
self.titleLayout.addWidget(self.iconLabel)
self.titleLayout.addWidget(self.titleLabel)
# Set layout
self.titleLayout.setContentsMargins(20, 10, 20, 0)
self.titleLayout.setSpacing(30)
self.titleLayout.setAlignment(QtCore.Qt.AlignCenter)
self.setLayout(self.titleLayout)
# Side Menu
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
# Customize widget
self.setObjectName("Option")
# Layout
optionLayout = QtWidgets.QHBoxLayout()
# Option font
optionFont = QtGui.QFont("Caviar Dreams")
optionFont.setPointSize(12)
optionFont.setBold(False)
optionFont.setLetterSpacing(QtGui.QFont.AbsoluteSpacing, 1.0)
# Set widgets
# Separator
optionSep = QtWidgets.QWidget()
optionSep.setStyleSheet("QWidget{background:#4da8e8;}")
optionSep.setFixedWidth(2)
# Doc button
docButton = QtWidgets.QPushButton()
docButton.setIcon(QtGui.QIcon(":/resources/doc.png"))
docButton.setIconSize(QtCore.QSize(40, 40))
docButton.setText("Documentation")
docButton.setFont(optionFont)
docButton.setCursor(QtCore.Qt.PointingHandCursor)
# Layout
optionLayout.addWidget(docButton, 10)
# self.optionLayout.setAlignment(QtCore.Qt.AlignCenter)
optionLayout.setContentsMargins(0, 0, 0, 0)
optionLayout.setSpacing(0)
optionLayout.setAlignment(QtCore.Qt.AlignCenter)
self.setLayout(optionLayout)
# Stylesheet
self.setStyleSheet("QWidget {margin: 0 0 0 0; padding: 0 0 0 0;} QPushButton{background:transparent; border:none; border-top: 2px solid #4da8e8; padding: 0 10px 0 10px; color: #ffffff; outline: none;} QPushButton:hover{background:#45c8dc;}")
# Actiond
docButton.clicked.connect(self.openDoc)
def setCallbackPlot(self, filedir):
self.plot_file = {}
# Delete previous widgets
for root, dir, files in os.walk(filedir):
for file in files:
if file.endswith(".png"):
filename = file.rsplit(".", 1)[0]
root_index = root.rsplit("/", 1)[1]
if root_index in self.plot_file:
if file != "ui.png":
self.plot_file[root_index].append(root + "/" + file)
else:
self.plot_file[root_index] = [root + "/ui.png"]
if file != "ui.png":
self.plot_file[root_index].append(root + "/" + file)
row_pos = col_pos = 0
for root_index in range(0, len(list(self.plot_file.keys()))):
row_pos = int(root_index/2)
col_pos = root_index % 2
root_name = list(self.plot_file.keys())[root_index]
currentfile = self.plot_file[root_name][0]
plot_frame = SubGraphViewer(self, root_name, currentfile)
self.plotViewer.addWidget(plot_frame, row_pos, col_pos, QtCore.Qt.AlignTop)
# self.plotViewer.addItem(QtWidgets.QSpacerItem(20, 60, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding), row_pos + 1, 0)
# self.graph_comboBox.setCurrentIndex(-1)
self.exportPlot_flag = -1
def __init__(self, parent = None):
QtWidgets.QMainWindow.__init__(self, parent)
self.setWindowFlags(QtCore.Qt.Widget)
def __init__(self, parent = None, root_name = "", currentfile = ""):
QtWidgets.QFrame.__init__(self, parent)
self.parent = parent
self.setMinimumHeight(400)
self.setMaximumHeight(400)
self.plot_font = QtGui.QFont('Bitter', 11)
self.setStyleSheet("QFrame{border: 2px solid #e9f0f5; border-radius:5px; border-left:4px solid #baddef;} QFrame:hover{border: 2px solid #faaba4; border-left:4px solid #fa7064; color: #55b1f2; }")
self.plot_layout = QtWidgets.QVBoxLayout()
self.plot_title_layout = QtWidgets.QHBoxLayout()
self.plot_title = QtWidgets.QLabel()
# Read only the name
self.plot_title.setText(root_name)
self.plot_title.setFont(self.plot_font)
self.plot_title.setStyleSheet("QLabel {border: none;}")
self.plot_title.setWordWrap(True)
self.plot_title_layout.insertStretch(0, 2)
self.plot_title_layout.addWidget(self.plot_title, 6)
self.plot_title_layout.insertStretch(2, 2)
self.plot_graph = GraphLabel()
self.plot_graph.setMargin(0)
self.plot_graph.setStyleSheet("QLabel{border: none;}")
self.currentdir = currentfile.rsplit("/", 1)[0]
self.currentpixmap = QtGui.QPixmap(currentfile).scaled(QtCore.QSize(300, 300))
self.plot_graph.setPixmap(self.currentpixmap)
self.plot_graph.setAlignment(QtCore.Qt.AlignCenter)
self.plot_layout.addWidget(self.plot_graph)
self.plot_layout.addLayout(self.plot_title_layout)
self.plot_layout.setContentsMargins(5, 5, 5, 10)
self.plot_layout.setSpacing(0)
self.setLayout(self.plot_layout)
self.root_name = root_name
# Click event
self.plot_graph.clicked.connect(self.openAllGraph)
# Display
# self.show()
def application(cls):
return PyQt5.Qt.qApp
def __init__(self, blocking=True):
self.object = res = PyQt5.Qt.QProgressDialog()
res.setVisible(False)
res.setWindowModality(blocking)
res.setAutoClose(True)
path = "{:s}/{:s}".format(database.path(), database.filename())
self.update(current=0, min=0, max=0, text='Processing...', tooltip='...', title=path)
# properties
def application(cls):
return PyQt5.Qt.qApp
def application(cls):
return PyQt5.Qt.qApp
#return PyQt5.Qt.QApplication.instance()
def preview_image_file(self, path):
filename = path.split('/')[-1]
if self.graphics_preview is None:
msg = "Graphics preview widget not created yet."
logger.critical(msg)
return
if not self.isVisible():
msg = "Preview widget invisible, not previewing image."
logger.info(msg)
return
self.setCurrentWidget(self.graphics_preview)
scene = QtWidgets.QGraphicsScene(self)
self.graphics_preview.setScene(scene)
# Using QImage instead of directly creating the QPixmap
# prevents a segmentation fault in my container setup
image = QtGui.QImage(path)
if image.isNull():
fmt = "File '{}' should be an image, but isn't."
msg = fmt.format(filename)
logger.error(msg)
return
pixmap = QtGui.QPixmap.fromImage(image)
if pixmap.isNull():
fmt = "Failed to generate pixmap from image '{}'."
msg = fmt.format(filename)
logger.critical(msg)
return
pixmap_item = QtWidgets.QGraphicsPixmapItem(pixmap)
scene.addItem(pixmap_item)
self.graphics_preview.fitInView(
pixmap_item,
Qt.Qt.KeepAspectRatio,
)
fmt = "Previewed file '{}' as an image."
msg = fmt.format(filename)
logger.info(msg)
def _init():
"""Try loading each binding in turn
Please note: the entire Qt module is replaced with this code:
sys.modules["Qt"] = binding()
This means no functions or variables can be called after
this has executed.
"""
preferred = os.getenv("QT_PREFERRED_BINDING")
verbose = os.getenv("QT_VERBOSE") is not None
bindings = (_pyside2, _pyqt5, _pyside, _pyqt4)
if preferred:
# Internal flag (used in installer)
if preferred == "None":
sys.modules[__name__].__wrapper_version__ = __version__
return
preferred = preferred.split(os.pathsep)
available = {
"PySide2": _pyside2,
"PyQt5": _pyqt5,
"PySide": _pyside,
"PyQt4": _pyqt4
}
try:
bindings = [available[binding] for binding in preferred]
except KeyError:
raise ImportError(
"Available preferred Qt bindings: "
"\n".join(preferred)
)
for binding in bindings:
_log("Trying %s" % binding.__name__[1:], verbose)
try:
sys.modules[__name__] = binding()
return
except ImportError as e:
_log(" - ImportError(\"%s\")\n" % e, verbose)
continue
# If not binding were found, throw this error
raise ImportError("No Qt binding were found.")
def __init__(self, parent=None):
QtWidgets.QListWidget.__init__(self, parent)
# Get parent
self.parent = parent
# List font
self.listFont = QtGui.QFont("Caviar Dreams")
self.listFont.setPointSize(14)
self.listFont.setBold(False)
self.listFont.setLetterSpacing(QtGui.QFont.AbsoluteSpacing, 1.0)
# Customize the widgets
self.setFocusPolicy(QtCore.Qt.NoFocus)
self.setFont(self.listFont)
self.horizontalScrollBar().setVisible(False)
self.setIconSize(QtCore.QSize(50, 50))
self.setFlow(QtWidgets.QListView.TopToBottom)
# Design icon
self.designIcon = QtGui.QIcon()
self.designIcon.addPixmap(QtGui.QPixmap(":/resources/design.png"), QtGui.QIcon.Normal)
self.designIcon.addPixmap(QtGui.QPixmap(":/resources/design_selected.png"), QtGui.QIcon.Selected)
"""
# Table?icon
self.tableIcon = QtGui.QIcon()
self.tableIcon.addPixmap(QtGui.QPixmap(":/resources/table.png"), QtGui.QIcon.Normal)
self.tableIcon.addPixmap(QtGui.QPixmap(":/resources/table_selected.png"), QtGui.QIcon.Selected)
"""
# Other icon
self.otherIcon = QtGui.QIcon()
self.otherIcon.addPixmap(QtGui.QPixmap(":/resources/other.png"), QtGui.QIcon.Normal)
self.otherIcon.addPixmap(QtGui.QPixmap(":/resources/other_selected.png"), QtGui.QIcon.Selected)
# Add design items
self.designItem = QtWidgets.QListWidgetItem(self.designIcon, "Design")
# self.tableItem = QtWidgets.QListWidgetItem(self.tableIcon, "Table")
self.otherItem = QtWidgets.QListWidgetItem(self.otherIcon, "Analyze")
# Add items to the list widget
self.addItem(self.designItem)
# self.addItem(self.tableItem)
self.addItem(self.otherItem)
# Stylesheet
self.setStyleSheet("QListWidget{min-width: 100px; border:none; border-top:2px solid #4da8e8; color:#ffffff; margin: 0 0 0 0; padding: 0 0 0 0; text-align:center;} QListWidget::item{border-bottom: 2px solid #4da8e8; padding:15px 25px 15px 25px; margin: 0 0 0 0; text-align: center; background:#399ee5; color:#ffffff;} QListWidget::item:hover{border:none; background:#45c8dc; font-weight:bold;} QListWidget::item:selected{border:none; border-left: 6px solid #fa7064; background:#ffffff; color:#fa7064; font-weight:bold;} QListWidget::icon{margin: 0 0 0 0; padding: 0 20px 0 0;} QLabel{background:transparent; border: none; font-size: 15pt; color:#ffffff; font-family:'Segoe UI';}")
# Action
# Select the tab, change the layout
self.currentRowChanged.connect(self.changeLayout)
# Change color
def openAllGraph(self):
self.plot_file_list = self.parent.plot_file[self.root_name]
self.graphviewer = QtWidgets.QFrame()
self.screen = QtWidgets.QDesktopWidget().screenGeometry()
# Set geometry
self.graphviewer.setGeometry(self.screen.width()/4, 100, 800, 600)
self.graphviewer.setWindowFlags(QtCore.Qt.Popup)
self.graphviewer.setObjectName("graphView")
self.graphviewer.setStyleSheet("QFrame#graphView{background:#ffffff;border:0.5px solid #fa7064;} QPushButton:hover{background:#6e66cc;border:1px solid #373366;} QToolButton:hover{background:#fa7064;}")
# self.graphviewer.setWindowModality(QtCore.Qt.WindowModal)
# Layout
graph_layout = QtWidgets.QVBoxLayout()
# Title
graph_title = SubTitleBar(self.graphviewer)
graph_title.title_Label.setText(self.root_name)
# Separator line
hline = QtWidgets.QWidget()
hline.setStyleSheet("QWidget{min-height:2px; max-height:2px; background:#399ee5;}")
# ComboBox
graph_control = QtWidgets.QWidget()
graph_control_layout = QtWidgets.QHBoxLayout()
self.graph_control_comboBox = QtWidgets.QComboBox()
self.graph_control_comboBox.setStyleSheet("QComboBox{font-family:'Segoe UI';font-size: 10pt;border: 1px solid #c5d2d9; border-radius:5px;padding: 5px 10px 5px 10px; color: #66767c;min-width: 250px;} QComboBox:hover{border: 2px solid #2a4d69;border-radius: 5px;height: 30ps;} QComboBox::drop-down {subcontrol-origin: padding; subcontrol-position: top right;width: 40px;border-left-width: 2px;border-left-color: #c5d2d9;border-left-style: solid; border-top-right-radius: 5px; border-bottom-right-radius: 5px;padding: 1px 1px 1px 1px;image: url(:/resources/dropdown_arrow.png);} QComboBox QAbstractItemView {border: 1px solid #c5d2d9; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px;selection-background-color:#4b86b4;outline: solid #2a4d69;font-family: 'Segoe UI';font-size: 10pt;color: #66767c;}")
graph_control_layout.insertStretch(0, 4)
graph_control_layout.addWidget(self.graph_control_comboBox)
graph_control_layout.insertStretch(3, 4)
graph_control.setLayout(graph_control_layout)
# Main Content
self.graph_content = QtWidgets.QStackedWidget()
# Add stack
for i in range(1, len(self.plot_file_list)):
currentName = self.plot_file_list[i].rsplit("/", 1)[1].rsplit(".", 1)[0]
self.graph_control_comboBox.addItem(currentName)
graph_label = QtWidgets.QLabel()
currentGraph = QtGui.QPixmap(self.plot_file_list[i])
graph_label.setPixmap(currentGraph)
graph_label.setAlignment(QtCore.Qt.AlignCenter)
self.graph_content.addWidget(graph_label)
# Add layout
graph_layout.addWidget(graph_title, 1)
graph_layout.addWidget(hline, 1)
graph_layout.addWidget(graph_control, 1)
graph_layout.addWidget(self.graph_content, 8)
graph_layout.setContentsMargins(5, 10, 5, 10)
graph_layout.setAlignment(QtCore.Qt.AlignTop)
self.graphviewer.setLayout(graph_layout)
self.graph_control_comboBox.currentIndexChanged.connect(self.changeGraph)
self.graphviewer.show()