Exemplo n.º 1
0
    def __init__(self, *args, **kwargs):

        super(Widget_objectList, self).__init__(*args, **kwargs)
        self.installEventFilter(self)
        mainLayout = QVBoxLayout(self)

        treeWidget = QTreeWidget()
        treeWidget.setColumnCount(2)
        headerItem = treeWidget.headerItem()
        headerItem.setText(0, "Target Node")
        headerItem.setText(1, "Attribute Name")
        treeWidget.setRootIsDecorated(False)
        treeWidget.setStyleSheet(
            "QTreeWidget::item { border-left: 1px solid gray;border-bottom: 1px solid gray; padding: 3px}\
                                 QTreeWidget{ font-size:13px;}")
        treeWidget.header().setStyleSheet("font-size:12px;")

        w_buttons = QWidget()
        lay_buttons = QHBoxLayout(w_buttons)
        lay_buttons.setContentsMargins(0, 0, 0, 0)
        lay_buttons.setSpacing(0)
        button_load = QPushButton("Load List")
        button_load.setStyleSheet("font:14px;")
        lay_buttons.addWidget(button_load)

        mainLayout.addWidget(treeWidget)
        mainLayout.addWidget(w_buttons)

        self.treeWidget = treeWidget
        QtCore.QObject.connect(
            treeWidget, QtCore.SIGNAL("itemChanged(QTreeWidgetItem * , int )"),
            self.writeData)
        QtCore.QObject.connect(button_load, QtCore.SIGNAL("clicked()"),
                               self.cmd_loadList)
Exemplo n.º 2
0
    def __init__(self, *args, **kwrgs):

        existing_widgets = Window.mayaWin.findChildren(QDialog,
                                                       Window.objectName)
        if existing_widgets: map(lambda x: x.deleteLater(), existing_widgets)

        super(Window, self).__init__(*args, **kwrgs)
        self.installEventFilter(self)
        self.setObjectName(Window.objectName)
        self.setWindowTitle(Window.title)

        mainLayout = QVBoxLayout(self)

        w_scriptPath = Widget_scriptPath()
        w_scriptPath.setStyleSheet("font-size:13px")
        w_textEditor = Widget_textEdit_splitter()
        w_button = QPushButton("RELOAD")
        w_button.setStyleSheet("font-size:14px")

        mainLayout.addWidget(w_scriptPath)
        mainLayout.addWidget(w_textEditor)
        mainLayout.addWidget(w_button)

        self.resize(Window.defaultWidth, Window.defaultHeight)
        self.load_shapeInfo(Window.path_uiInfo)

        w_button.clicked.connect(self.cmd_reload)

        self.w_scriptPath = w_scriptPath
        self.w_textEditor = w_textEditor

        w_textEditor.load_leftScript()
        w_textEditor.load_convertedText()
Exemplo n.º 3
0
    def __init__(self, *args, **kwargs):

        self.saveInfo = False
        self.title = ''
        if kwargs.has_key('title'):
            self.title = kwargs.pop('title')
        if kwargs.has_key('saveInfo'):
            self.saveInfo = kwargs.pop('saveInfo')

        self.path_uiInfo = path_basedir + "/Widget_Controller_%s.json" % self.title

        super(Widget_loadObject, self).__init__(*args, **kwargs)
        self.installEventFilter( self )
        mainLayout = QHBoxLayout(self)

        self.setStyleSheet( "font:12px;" )
        label = QLabel( "%s : " % self.title ); label.setFixedWidth( 80 )
        lineEdit = QLineEdit(); lineEdit.setStyleSheet( "padding:2px; padding-bottom:1px" )
        button = QPushButton( "Load" ); button.setFixedWidth( 70 )
        button.setStyleSheet( "padding:3px;padding-left:6px;padding-right:6px" )

        mainLayout.addWidget( label )
        mainLayout.addWidget( lineEdit )
        mainLayout.addWidget( button )

        button.clicked.connect( self.load_target )
        self.lineEdit = lineEdit
        if self.saveInfo : self.load_lineEdit_text( self.lineEdit, self.path_uiInfo )

        self.button = button
Exemplo n.º 4
0
    def __init__(self, presenter, parent=None):
        super(MainView, self).__init__(presenter, parent=parent)
        self.setLayout(QGridLayout())

        addEffects = QPushButton(self)
        addEffects.isWordWrap = False
        addEffects.setFlat(True)
        addEffects.setCursor(Qt.PointingHandCursor)
        addEffects.setStyleSheet("QPushButton{outline:0; border-radius: 0px}")
        addEffects.setIcon(QPixmap("gui\\Add-Effects.png"))
        addEffects.setIconSize(QSize(300, 50))

        self.layout().addWidget(addEffects, 0, 0, 1, 1)
        self.setMinimumSize(QSize(640, 480))

        addEffects.clicked.connect(self.addEffectsClicked)
Exemplo n.º 5
0
    def __init__(self, *args, **kwargs):

        super(Widget_Controller, self).__init__(*args, **kwargs)
        self.installEventFilter(self)
        mainLayout = QHBoxLayout(self)

        self.setStyleSheet("font:12px;")
        label = QLabel("Controller : ")
        lineEdit = QLineEdit()
        lineEdit.setStyleSheet("padding:2px; padding-bottom:1px")
        button = QPushButton("Load Controller")
        button.setStyleSheet("padding:3px;padding-left:6px;padding-right:6px")

        mainLayout.addWidget(label)
        mainLayout.addWidget(lineEdit)
        mainLayout.addWidget(button)

        button.clicked.connect(self.load_Controller)
        self.lineEdit = lineEdit
Exemplo n.º 6
0
class FolderSelector(QWidget):
    def __init__(self, var_name, default_folder, project_root_dir = "", help_instance=None, handler=None):
        QWidget.__init__(self)
        self.project_root_dir = project_root_dir
        self.my_layout = QHBoxLayout()
        self.setLayout(self.my_layout)
        self.var_name = var_name
        self.current_value = default_folder
        self.full_path = project_root_dir + default_folder
        self.project_root_dir = project_root_dir

        self.handler=handler
        self.my_but = QPushButton(os.path.basename(remove_trailing_slash(default_folder)))
        self.my_but.setFont(regular_small_font)
        self.my_but.setStyleSheet("text-align: left")
        self.my_but.clicked.connect(self.set_folder)
        self.my_layout.addWidget(self.my_but)

        my_label = QLabel(var_name)
        my_label.setFont(regular_small_font)
        self.my_layout.addWidget(my_label)

    def set_folder(self):
        directions = "Select a folder for " + self.var_name
        new_value = QFileDialog.getExistingDirectory(self, directions, dir=os.path.dirname(self.full_path), options=QFileDialog.ShowDirsOnly)
        new_value = re.sub(self.project_root_dir, "", new_value)
        self.set_myvalue(new_value)
        if self.handler is not None:
            self.handler()

    def get_myvalue(self):
        return self.current_value

    def set_myvalue(self, new_value):
        if new_value != "":
            self.current_value = new_value
            self.full_path = add_slash(self.project_root_dir + new_value)
            self.my_but.setText(os.path.basename(remove_trailing_slash(self.current_value)))

    value = property(get_myvalue, set_myvalue)
Exemplo n.º 7
0
    def __init__(self, *args, **kwrgs):

        existing_widgets = Window.mayaWin.findChildren(QDialog,
                                                       Window.objectName)
        if existing_widgets: map(lambda x: x.deleteLater(), existing_widgets)

        super(Window, self).__init__(*args, **kwrgs)

        self.installEventFilter(self)
        self.setObjectName(Window.objectName)
        self.setWindowTitle(Window.title)
        mainLayout = QVBoxLayout(self)

        w_splitter = Widget_splitter(QtCore.Qt.Vertical)
        w_typeAttrList = Widget_TypeAttributeList()
        w_fileTree = Widget_FileTree()
        button_refresh = QPushButton("REFRESH".decode('utf-8'))
        button_refresh.setStyleSheet("font-size:13px")

        w_splitter.addWidget(w_typeAttrList)
        w_splitter.addWidget(w_fileTree)

        mainLayout.addWidget(w_splitter)
        mainLayout.addWidget(button_refresh)
        button_refresh.setFocus()

        self.w_typeAttrList = w_typeAttrList
        self.w_fileTree = w_fileTree

        self.resize(Window.defaultWidth, Window.defaultHeight)
        self.load_shapeInfo(Window.path_uiInfo)

        QtCore.QObject.connect(button_refresh, QtCore.SIGNAL("clicked()"),
                               self.w_fileTree.loadList)
        self.w_fileTree.w_typeAttrList = self.w_typeAttrList
        self.w_fileTree.loadList()

        self.w_typeAttrList.appendCheckEventCommands(self.w_fileTree.loadList)
        w_splitter.loadSplitterPosition()
Exemplo n.º 8
0
class ActualFakeActuator(object):
    def __init__(self, callback=None):
        self.callback = callback

        self.app = QApplication(sys.argv)

        self.vlayout = QVBoxLayout()

        self.button = QPushButton('light')
        self.button.pressed.connect(self._button_callback)
        self.button.setCheckable(True)
        self.button.setChecked(True)
        self.button.setStyleSheet('background-color: white')
        self.vlayout.addWidget(self.button)

        self.slider = QSlider()
        self.slider.setOrientation(Qt.Horizontal)
        self.vlayout.addWidget(self.slider)

        self.dial = QDial()
        self.dial.setNotchesVisible(True)
        self.dial.setWrapping(True)
        self.vlayout.addWidget(self.dial)

        self.quit = QPushButton('Quit')
        self.quit.clicked.connect(self.app.quit)
        self.vlayout.addWidget(self.quit)

        self.group = QGroupBox('Fake Actuator')
        self.group.setLayout(self.vlayout)

    def _button_callback(self):
        if self.button.isChecked():
            self.button.setStyleSheet('background-color: red')
        else:
            self.button.setStyleSheet('background-color: white')

    def light_on(self):
        return self.button.isChecked()

    def toggle_light(self, on):
        self.button.setChecked(on)

    def volume(self):
        return self.slider.value()

    def set_volume(self, value):
        self.slider.setValue(value)

    def position(self):
        return self.dial.value()

    def set_position(self, value):
        self.dial.setValue(value)

    def run(self):
        self.group.show()
        self.app.exec_()
Exemplo n.º 9
0
class FileSelector(QWidget):
    def __init__(self, var_name, default_file, project_root_dir = None, help_instance=None):
        QWidget.__init__(self)
        self.project_root_dir = project_root_dir
        self.my_layout = QHBoxLayout()
        self.setLayout(self.my_layout)
        self.var_name = var_name
        self.current_value = default_file
        self.full_path = project_root_dir + default_file
        self.my_layout.setContentsMargins(1, 1, 1, 1)
        self.my_layout.setSpacing(3)

        self.my_but = QPushButton(os.path.basename(remove_trailing_slash(default_file)))
        self.my_but.setFont(regular_small_font)
        self.my_but.setStyleSheet("text-align: left")
        self.my_but.clicked.connect(self.set_file)
        self.my_layout.addWidget(self.my_but)

        my_label = QLabel(var_name)
        my_label.setFont(regular_small_font)
        self.my_layout.addWidget(my_label)

    def set_file(self):
        directions = "Select a file for " + self.var_name
        new_value = QFileDialog.getOpenFileName(self, directions, dir=os.path.dirname(self.full_path))[0]
        new_value = re.sub(self.project_root_dir, "", new_value)
        self.set_myvalue(new_value)

    def get_myvalue(self):
        return self.current_value

    def set_myvalue(self, new_value):
        if new_value != "":
            self.current_value = new_value
            self.my_but.setText(os.path.basename(remove_trailing_slash(self.current_value)))

    value = property(get_myvalue, set_myvalue)
Exemplo n.º 10
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        #widnow setup
        resolution = QDesktopWidget().screenGeometry()
        self.screen_w = resolution.width()
        self.screen_h = resolution.height()
        self.setGeometry(0, 0, 650, 200)
        self.setWindowTitle('bento dumper' + mof.get_version_suffix())
        self.setWindowIcon(QIcon('icons/run.png'))

        #center window
        qr = self.frameGeometry()
        cp = QtGui.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        #adjust size
        self.resize(self.screen_w / 2, self.screen_h / 16)
        self.Menu()
        self.Layout()

        central_widget = QtGui.QWidget()
        central_widget.setLayout(self.main_layout)
        self.setCentralWidget(central_widget)

    def Menu(self):
        #this creates an action exit, a shortcut and status tip
        exitAction = QAction(QIcon('icons/exit.png'), '&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)

        openFile = QAction(QIcon('icons/open.png'), '&Open', self)
        openFile.setShortcut('Ctrl+O')
        openFile.setStatusTip('Open new File')
        openFile.triggered.connect(self.browse)

        runAction = QAction(QIcon('icons/run.png'), '&Run', self)
        runAction.setShortcut('Ctrl+R')
        runAction.setStatusTip('Run Mars')
        runAction.triggered.connect(self.run_event)

    def Layout(self):
        #LAYOUT
        self.directory_prompt = QLabel(self)
        self.directory_prompt.setText("Directory Selected:")
        self.directory_prompt.move(25, 50)
        self.directory_prompt.resize(150, 30)

        self.browse_btn = QPushButton("Browse", self)
        self.browse_btn.move(130, 50)
        self.browse_btn.setStatusTip(" Browse Folder")
        # self.browse_btn.setStyleSheet("background-color: rgb(186, 186, 186); border-radius: 15px;border-style: solid;border-width: 2px;border-color: black;");
        self.browse_btn.clicked.connect(self.browse)

        self.dir_shower = QLabel(self)
        self.dir_shower.setText("Directory")

        self.run_mars = QPushButton("Dump BENTO", self)
        self.run_mars.setVisible(True)
        self.run_mars.move(25, 160)
        self.run_mars.resize(self.screen_w / 2 - 150, 50)
        self.run_mars.setStatusTip('')
        self.run_mars.setStyleSheet(
            "background-color: rgb(142, 229, 171); border-radius: 15px;")
        self.run_mars.clicked.connect(self.run_event)

        self.menu_layout = QtGui.QHBoxLayout()
        self.menu_layout.addWidget(self.browse_btn)
        self.menu_layout.addWidget(self.directory_prompt)
        self.menu_layout.addWidget(self.dir_shower)
        self.menu_layout.addStretch()

        self.run_layout = QtGui.QHBoxLayout()
        self.run_layout.addWidget(self.run_mars)

        self.main_layout = QtGui.QVBoxLayout()
        self.main_layout.addLayout(self.menu_layout)
        self.main_layout.addLayout(self.run_layout)

        self.main_layout.addStretch()

    def browse(self):
        # sender = self.sender()
        dialog = QtGui.QFileDialog()
        dialog.setFileMode(QtGui.QFileDialog.Directory)
        dialog.setOption(QtGui.QFileDialog.ShowDirsOnly)
        self.dirname = dialog.getExistingDirectory(self, 'Choose Directory',
                                                   os.path.curdir)
        if os.path.exists(self.dirname) and os.path.isdir(self.dirname):
            self.dir_shower.setText(self.dirname)
            return
        else:
            QMessageBox.information(self, " Wrong file selected",
                                    "Select a folder containing .seq files!")

    def run_event(self):
        self.genericThread = GenericThread(self.dirname)
        self.genericThread.start()
Exemplo n.º 11
0
class WidgetTest(QWidget):

    sig_exec = OrcSignal()

    def __init__(self):

        QWidget.__init__(self)

        self.__dict = LibDict()
        self.__service = WebMainService()

        self.id = None
        self.type = None
        self.operation = None
        self.data = None
        self.env = None

        # 输入框
        _layout_top = QGridLayout()

        self.__edit_type = OrcSelect()  # 类型,页面或者控件
        self.__edit_flag = OrcLineEdit()  # 标识符
        self.__widget_type = SelectWidgetType(True)  # 控件类型
        self.__widget_ope = SelectWidgetOperation(True)  # 控件操作类型
        self.__widget_data = OrcLineEdit()

        self.__edit_type.set_empty()
        self.__edit_type.set_flag("operate_object_type")
        self.__edit_type.setEnabled(False)
        self.__edit_flag.setEnabled(False)
        self.__widget_type.setEnabled(False)
        self.__widget_data.setEnabled(False)

        _layout_top.addWidget(QLabel(u"类型:"), 0, 0)
        _layout_top.addWidget(self.__edit_type, 0, 1)
        _layout_top.addWidget(QLabel(u"标识:"), 1, 0)
        _layout_top.addWidget(self.__edit_flag, 1, 1)
        _layout_top.addWidget(QLabel(u"控件:"), 2, 0)
        _layout_top.addWidget(self.__widget_type, 2, 1)
        _layout_top.addWidget(QLabel(u"操作:"), 3, 0)
        _layout_top.addWidget(self.__widget_ope, 3, 1)
        _layout_top.addWidget(QLabel(u"数据:"), 4, 0)
        _layout_top.addWidget(self.__widget_data, 4, 1)

        self.__edit_status = OrcTextArea(self)
        self.__edit_status.setReadOnly(True)

        # 按钮
        _layout_button = QHBoxLayout()

        self.__btn_exec = QPushButton(u"执行")
        self.__btn_exec.setStyleSheet(get_theme("Buttons"))

        _layout_button.addStretch()
        _layout_button.addWidget(self.__btn_exec)

        # 主界面
        _layout = QVBoxLayout()
        _layout.addLayout(_layout_top)
        _layout.addWidget(self.__edit_status)
        _layout.addLayout(_layout_button)

        self.setLayout(_layout)

        self.__widget_ope.currentIndexChanged.connect(self.__set_operation)
        self.__widget_data.textChanged.connect(self.__set_data)
        self.__btn_exec.clicked.connect(self.sig_exec.emit)

    def __set_operation(self):

        _ope = self.__widget_ope.get_data()

        if not _ope:
            self.operation = None
        else:
            self.operation = _ope

    def __set_data(self):
        self.data = self.__widget_data.get_data()

    def set_type(self, p_type, p_id):

        # 设置对象类型
        _type_text = self.__dict.get_dict("operate_object_type",
                                          p_type)[0].dict_text
        self.__edit_type.set_data(_type_text)

        self.id = p_id
        self.type = p_type

        if "PAGE" == p_type:

            _page_id, _page_flg, _page_env = self.__service.get_page_key(p_id)
            _page_key = "%s[%s]" % (_page_flg, _page_env)

            self.id = _page_id
            self.env = _page_env

            # 设置页面标识
            self.__edit_flag.set_data(_page_key)

            # 禁用控件类型
            self.__widget_type.set_data("")

            # 页面操作项
            self.__widget_ope.set_type("PAGE")
            # self.__widget_ope.setEnabled(False)

            # 禁止输入数据
            self.__widget_data.clear()
            self.__widget_data.setEnabled(False)

        elif "WIDGET" == p_type:

            _widget_key = self.__service.get_widget_key(p_id)
            _widget_type = self.__service.get_widget_type(p_id)

            # 设置控件标识
            self.__edit_flag.set_data(_widget_key)

            # 设置控件类型
            self.__widget_type.set_data(_widget_type)

            # 重置控件操作项
            self.__widget_ope.set_type(_widget_type)
            # self.__widget_ope.setEnabled(True)

            # 数据输入框可用
            self.__widget_data.setEnabled(True)

        else:
            pass

    def set_env(self, p_env):
        self.env = p_env

    def set_status(self, p_status):

        if p_status:
            self.__edit_status.setText("Success")
        else:
            self.__edit_status.setText("Fail")
Exemplo n.º 12
0
class CookieCutterWidget(QWidget):
    "CookieCutter UI"

    FILE_FILTER = u'Inselect cookie cutter (*{0})'.format(
        CookieCutter.EXTENSION
    )

    def __init__(self, parent=None):
        super(CookieCutterWidget, self).__init__(parent)

        # Configure the UI
        self._create_actions()
        self.button = QPushButton("Cookie cutter")
        self.button.setMaximumWidth(250)
        self.button.setStyleSheet("text-align: left")
        self.popup = QMenu()
        self.inject_actions(self.popup)
        self.button.setMenu(self.popup)

        layout = QHBoxLayout()
        layout.addWidget(self.button)
        self.setLayout(layout)

    def _create_actions(self):
        self.save_to_new_action = QAction(
            "Save boxes to new cookie cutter...", self
        )
        self.choose_action = QAction(
            "Choose...", self, triggered=self.choose
        )
        self.clear_action = QAction(
            "Do not use a cookie cutter", self, triggered=self.clear
        )
        self.apply_current_action = QAction("Apply", self)

    def inject_actions(self, menu):
        "Adds cookie cutter actions to menu"
        menu.addAction(self.choose_action)
        menu.addAction(self.apply_current_action)
        menu.addSeparator()
        menu.addAction(self.clear_action)
        menu.addSeparator()
        menu.addAction(self.save_to_new_action)

    @report_to_user
    def clear(self):
        "Clears the choice of cookie cutter"
        cookie_cutter_choice().clear()

    @report_to_user
    def choose(self):
        "Shows a 'choose cookie cutter' file dialog"
        debug_print('CookieCutterWidget.choose_cookie_cutter')
        path, selectedFilter = QFileDialog.getOpenFileName(
            self, "Choose cookie cutter",
            unicode(cookie_cutter_choice().last_directory()),
            self.FILE_FILTER
        )

        if path:
            # Save the user's choice
            cookie_cutter_choice().load(path)

    def sync_actions(self, has_document, has_rows):
        "Sync state of actions"
        debug_print('CookieCutterWidget.sync_ui')
        current = cookie_cutter_choice().current
        has_current = cookie_cutter_choice().current is not None
        name = current.name if current else 'Cookie cutter'

        # Truncate text to fit button
        metrics = QFontMetrics(self.button.font())
        elided = metrics.elidedText(
            name, Qt.ElideRight, self.button.width() - 25
        )
        self.button.setText(elided)

        self.save_to_new_action.setEnabled(has_rows)
        self.clear_action.setEnabled(has_current)
        self.apply_current_action.setEnabled(has_document and has_current)
Exemplo n.º 13
0
class ui(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.setupUI()
        self.id = 1
        self.lines = []
        self.editable = True
        self.des_sort = True
        self.faker = Factory.create()
        self.btn_add.clicked.connect(self.add_line)
        self.btn_del.clicked.connect(self.del_line)
        self.btn_modify.clicked.connect(self.modify_line)
        self.btn_select_line.clicked.connect(self.select_line)
        self.btn_select_single.clicked.connect(self.deny_muti_line)
        self.btn_sort.clicked.connect(self.sortItem)
        self.btn_set_header.clicked.connect(self.setheader)
        self.btn_set_middle.clicked.connect(self.middle)
        self.table.cellChanged.connect(self.cellchange)
        self.btn_noframe.clicked.connect(self.noframe)


#     # Sess = sessionmaker(bind = engine)

    def setupUI(self):
        self.setWindowTitle(windowTital)
        self.resize(640, 480)
        self.table = QTableWidget(self)
        self.btn_add = QPushButton(u'增加')
        self.btn_del = QPushButton(u'删除')
        self.btn_modify = QPushButton(u'可以编辑')
        self.btn_select_line = QPushButton(u'选择整行')
        self.btn_select_single = QPushButton(u'禁止选多行')
        self.btn_sort = QPushButton(u'以分数排序')
        self.btn_set_header = QPushButton(u'标头设置')
        self.btn_set_middle = QPushButton(u'文字居中加颜色')
        self.btn_noframe = QPushButton(u'取消边框颜色交替')
        self.spacerItem = QSpacerItem(20, 20, QSizePolicy.Minimum,
                                      QSizePolicy.Expanding)
        self.vbox = QVBoxLayout()
        self.vbox.addWidget(self.btn_add)
        self.vbox.addWidget(self.btn_del)
        self.vbox.addWidget(self.btn_modify)
        self.vbox.addWidget(self.btn_select_line)
        self.vbox.addWidget(self.btn_select_single)
        self.vbox.addWidget(self.btn_sort)
        self.vbox.addWidget(self.btn_set_header)
        self.vbox.addWidget(self.btn_set_middle)
        self.vbox.addWidget(self.btn_noframe)
        self.vbox.addSpacerItem(
            self.spacerItem)  #可以用addItem也可以用addSpacerItem方法添加,没看出哪里不一样
        self.txt = QLabel()
        self.txt.setMinimumHeight(50)
        self.vbox2 = QVBoxLayout()
        self.vbox2.addWidget(self.table)
        self.vbox2.addWidget(self.txt)
        self.hbox = QHBoxLayout()
        self.hbox.addLayout(self.vbox2)
        self.hbox.addLayout(self.vbox)
        self.setLayout(self.hbox)
        self.table.setColumnCount(4)  ##设置列数
        self.headers = [u'id', u'选择', u'姓名', u'成绩', u'住址']
        self.table.setHorizontalHeaderLabels(self.headers)
        self.show()

    def add_line(self):
        self.table.cellChanged.disconnect()
        row = self.table.rowCount()
        self.table.setRowCount(row + 1)
        id = str(self.id)
        ck = QCheckBox()
        h = QHBoxLayout()
        h.setAlignment(Qt.AlignCenter)
        h.addWidget(ck)
        w = QWidget()
        w.setLayout(h)
        name = self.faker.name()
        score = str(random.randint(50, 99))
        add = self.faker.address()
        self.table.setItem(row, 0, QTableWidgetItem(id))
        self.table.setCellWidget(row, 1, w)
        self.table.setItem(row, 2, QTableWidgetItem(name))
        self.table.setItem(row, 3, QTableWidgetItem(score))
        self.table.setItem(row, 4, QTableWidgetItem(add))
        self.id += 1
        self.lines.append([id, ck, name, score, add])
        self.settext(u'自动生成随机一行数据!,checkbox设置为居中显示')
        self.table.cellChanged.connect(self.cellchange)

    def del_line(self):
        removeline = []
        for line in self.lines:
            if line[1].isChecked():
                row = self.table.rowCount()
                for x in range(row, 0, -1):
                    if line[0] == self.table.item(x - 1, 0).text():
                        self.table.removeRow(x - 1)
                        removeline.append(line)
        for line in removeline:
            self.lines.remove(line)
        self.settext(u'删除在左边checkbox中选中的行,使用了一个笨办法取得行号\n,不知道有没有其他可以直接取得行号的方法!')

    def modify_line(self):
        if self.editable == True:
            self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
            self.btn_modify.setText(u'禁止编辑')
            self.editable = False
        else:
            self.table.setEditTriggers(QAbstractItemView.AllEditTriggers)
            self.btn_modify.setText(u'可以编辑')
            self.editable = True
        self.settext(u'设置,是否可以编辑整个表格')

    def select_line(self):
        if self.table.selectionBehavior() == 0:
            self.table.setSelectionBehavior(1)
            self.btn_select_line.setStyleSheet('background-color:lightblue')
        else:
            self.table.setSelectionBehavior(0)
            self.btn_select_line.setStyleSheet('')
        self.settext(u'默认时,点击单元格,只可选择一个格,此处设置为可选择整行')

    def deny_muti_line(self):
        if self.table.selectionMode() in [2, 3]:
            self.table.setSelectionMode(QAbstractItemView.SingleSelection)
            self.btn_select_single.setStyleSheet('background-color:lightblue')
        else:
            self.table.setSelectionMode(QAbstractItemView.ExtendedSelection)
            self.btn_select_single.setStyleSheet('')
        self.settext(u'点击时会轮换以多行或单行选择,默认是可以同时选择多行')

    def sortItem(self):
        if self.des_sort == True:
            self.table.sortItems(3, Qt.DescendingOrder)
            self.des_sort = False
            self.btn_sort.setStyleSheet('background-color:lightblue')
            self.table.setSortingEnabled(True)  # 设置表头可以自动排序
        else:
            self.table.sortItems(3, Qt.AscendingOrder)
            self.des_sort = True
            self.btn_sort.setStyleSheet('background-color:lightblue')
            self.table.setSortingEnabled(False)
        self.settext(u'点击时会轮换以升序降序排列,但排序时,会使自动列宽失效!')

    def setheader(self):
        font = QFont(u'微软雅黑', 12)
        font.setBold(True)
        self.table.horizontalHeader().setFont(font)  # 设置表头字体
        self.table.setColumnWidth(0, 50)
        self.table.setColumnWidth(1, 50)
        self.table.setColumnWidth(3, 100)
        self.table.horizontalHeader().setSectionResizeMode(
            2, QHeaderView.Stretch)
        self.table.horizontalHeader().setStyleSheet(
            'QHeaderView::section{background:gray}')
        self.table.horizontalHeader().setFixedHeight(50)
        self.table.setColumnHidden(0, True)
        self.btn_set_header.setStyleSheet('background-color:lightblue')
        self.settext(
            u'设置标头字体及字号,隐藏ID列,设置标头除姓名外全部为固定宽度\n,设置姓名列自动扩展宽度,设置标头行高,设置标头背景色')

    def middle(self):
        self.btn_set_middle.setStyleSheet('background-color:lightblue')
        self.table.setStyleSheet('color:green;')
        row = self.table.rowCount()
        for x in range(row):
            for y in range(4):
                if y != 1:
                    item = self.table.item(x, y)
                    item.setTextAlignment(Qt.AlignCenter)
                else:
                    pass
        self.btn_set_middle.setStyleSheet('background-color:lightblue')
        self.settext(u'将文字居中显示,设置文字颜色')

    def cellchange(self, row, col):
        item = self.table.item(row, col)
        txt = item.text()
        self.settext(u'第%s行,第%s列 , 数据改变为:%s' % (row, col, txt))

    def noframe(self):
        self.table.setAlternatingRowColors(True)
        self.table.setFrameStyle(QFrame.NoFrame)
        self.table.setStyleSheet('color:green;'
                                 'gridline-color:white;'
                                 'border:0px solid gray')
        self.settext(u'取消表的框线,\n 取消表格内框')

    def settext(self, txt):
        font = QFont(u'微软雅黑', 10)
        self.txt.setFont(font)
        self.txt.setText(txt)
Exemplo n.º 14
0
class TransferPanel(QWidget):
    '''
    Transfer Panel
    
    This Panel is the main dialog box for the Dive Computer Transfer GUI
    '''
    def __init__(self, parent=None):
        super(TransferPanel, self).__init__(parent)
        
        self._logbook = None
        self._logbookName = 'None'
        self._logbookPath = None
        
        self._createLayout()
        
        self._readSettings()
        self.setWindowTitle(self.tr('DC Transfer - %s') % self._logbookName)
        
    def _createLayout(self):
        'Create the Widget Layout'
        
        self._txtLogbook = QLineEdit()
        self._txtLogbook.setReadOnly(True)
        self._lblLogbook = QLabel(self.tr('&Logbook File:'))
        self._lblLogbook.setBuddy(self._txtLogbook)
        self._btnBrowse = QPushButton('...')
        self._btnBrowse.clicked.connect(self._btnBrowseClicked)
        self._btnBrowse.setStyleSheet('QPushButton { min-width: 24px; max-width: 24px; }')
        self._btnBrowse.setToolTip(self.tr('Browse for a Logbook'))
        
        self._cbxComputer = QComboBox()
        self._lblComputer = QLabel(self.tr('Dive &Computer:'))
        self._lblComputer.setBuddy(self._cbxComputer)
        self._btnAddComputer = QPushButton(QPixmap(':/icons/list-add.png'), self.tr(''))
        self._btnAddComputer.setStyleSheet('QPushButton { min-width: 24px; min-height: 24; max-width: 24px; max-height: 24; }')
        self._btnAddComputer.clicked.connect(self._btnAddComputerClicked)
        self._btnRemoveComputer = QPushButton(QPixmap(':/icons/list-remove.png'), self.tr(''))
        self._btnRemoveComputer.setStyleSheet('QPushButton { min-width: 24px; min-height: 24; max-width: 24px; max-height: 24; }')
        self._btnRemoveComputer.clicked.connect(self._btnRemoveComputerClicked)
        
        hbox = QHBoxLayout()
        hbox.addWidget(self._btnAddComputer)
        hbox.addWidget(self._btnRemoveComputer)
        
        gbox = QGridLayout()
        gbox.addWidget(self._lblLogbook, 0, 0)
        gbox.addWidget(self._txtLogbook, 0, 1)
        gbox.addWidget(self._btnBrowse, 0, 2)
        gbox.addWidget(self._lblComputer, 1, 0)
        gbox.addWidget(self._cbxComputer, 1, 1)
        gbox.addLayout(hbox, 1, 2)
        gbox.setColumnStretch(1, 1)
        
        self._pbTransfer = QProgressBar()
        self._pbTransfer.reset()
        self._txtStatus = QTextEdit()
        self._txtStatus.setReadOnly(True)
        
        self._btnTransfer = QPushButton(self.tr('&Transfer Dives'))
        self._btnTransfer.clicked.connect(self._btnTransferClicked)
        
        self._btnExit = QPushButton(self.tr('E&xit'))
        self._btnExit.clicked.connect(self.close)
        
        hbox = QHBoxLayout()
        hbox.addWidget(self._btnTransfer)
        hbox.addStretch()
        hbox.addWidget(self._btnExit)
        
        vbox = QVBoxLayout()
        vbox.addLayout(gbox)
        vbox.addWidget(self._pbTransfer)
        vbox.addWidget(self._txtStatus)
        vbox.addLayout(hbox)
        
        self.setLayout(vbox)
        
    def _closeLogbook(self):
        'Close the current Logbook'
        if self._logbook is None:
            return
        
        self._logbook = None
        self._logbookName = 'None'
        self._logbookPath = None
        
        self._txtLogbook.clear()
        self._cbxComputer.setModel(None)
        
        self._writeSettings()
        self.setWindowTitle(self.tr('DC Transfer - %s') % self._logbookName)
        
    def _openLogbook(self, path):
        'Open an existing Logbook'
        if self._logbook is not None:
            self._closeLogbook()
            
        if not os.path.exists(path):
            QMessageBox.critical(self, self.tr('Missing Logbook'), 
                self.tr('Logbook File "%s" does not exist.') % path)
            return
        
        #TODO: Handle a Schema Upgrade in a user-friendly manner
        self._logbook = Logbook(path, auto_update=False)
        self._logbookName = os.path.basename(path)
        self._logbookPath = path
        
        self._txtLogbook.setText(self._logbookPath)
        self._cbxComputer.setModel(DiveComputersModel(self._logbook))
        
        self._writeSettings()
        self.setWindowTitle(self.tr('DC Transfer - %s') % self._logbookName)
        
    def _readSettings(self):
        'Read main window settings from the configuration'
        settings = QSettings()
        settings.beginGroup('MainWindow')
        max = settings.value('max')
        size = settings.value('size')
        pos = settings.value('pos')
        file = settings.value('file')
        settings.endGroup()
        
        # Size and Position the Main Window
        if size is not None:
            self.resize(size)
        if pos is not None:
            self.move(pos)
            
        # HAX because QVariant is not exposed in PySide and the default
        # coercion to string is just stupid
        if max is not None and (max == 'true'):
            self.showMaximized()
        
        # Open the Logbook
        if file is not None:
            self._openLogbook(file)
        
    def _writeSettings(self):
        'Write settings to the configuration'
        settings = QSettings()
        settings.beginGroup('MainWindow')
        settings.setValue('pos', self.pos())
        settings.setValue('size', self.size())
        settings.setValue('max', self.isMaximized())
        settings.setValue('file', self._logbookPath)
        settings.endGroup()
        
    def closeEvent(self, e):
        'Intercept an OnClose event'
        self._writeSettings()
        e.accept()
        
    #--------------------------------------------------------------------------
    # Slots
    
    @QtCore.Slot()
    def _btnAddComputerClicked(self):
        'Add a Dive Computer'
        dc = AddDiveComputerWizard.RunWizard(self)
        
        if dc is not None:
            self._logbook.session.add(dc)
            self._logbook.session.commit()
            self._cbxComputer.model().reload()
            self._cbxComputer.setCurrentIndex(self._cbxComputer.findText(dc.name))
    
    @QtCore.Slot()
    def _btnRemoveComputerClicked(self):
        'Remove a Dive Computer'
        idx = self._cbxComputer.currentIndex()
        dc = self._cbxComputer.itemData(idx, Qt.UserRole+0)
        if QMessageBox.question(self, self.tr('Delete Dive Computer?'), 
                    self.tr('Are you sure you want to delete "%s"?') % dc.name,
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) == QMessageBox.Yes:
            self._logbook.session.delete(dc)
            self._logbook.session.commit()
            self._cbxComputer.model().reload()
    
    @QtCore.Slot()
    def _btnBrowseClicked(self):
        'Browse for a Logbook File'
        if self._logbook is not None:
            dir = os.path.dirname(self._logbookPath)
        else:
            dir = os.path.expanduser('~')
        
        fn = QFileDialog.getOpenFileName(self,
            caption=self.tr('Select a Logbook file'), dir=dir,
            filter='Logbook Files (*.lbk);;All Files(*.*)')[0]    
        if fn == '':
            return
        if not os.path.exists(fn):
            if QMessageBox.question(self, self.tr('Create new Logbook?'), 
                    self.tr('Logbook "%s" does not exist. Would you like to create it?') % os.path.basename(fn),
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) != QMessageBox.Yes:
                return
            Logbook.Create(fn)
        self._openLogbook(fn)
        
    @QtCore.Slot()
    def _btnTransferClicked(self):
        'Transfer Dives'
        idx = self._cbxComputer.currentIndex()
        dc = self._cbxComputer.itemData(idx, Qt.UserRole+0)
        
        if self._logbook.session.dirty:
            print "Flushing dirty session"
            self._logbook.rollback()
        
        self._txtLogbook.setEnabled(False)
        self._btnBrowse.setEnabled(False)
        self._cbxComputer.setEnabled(False)
        self._btnAddComputer.setEnabled(False)
        self._btnRemoveComputer.setEnabled(False)
        self._btnTransfer.setEnabled(False)
        self._btnExit.setEnabled(False)
        
        self._txtStatus.clear()
        
        thread = QThread(self)
        
        #FIXME: ZOMG HAX: Garbage Collector will eat TransferWorker when moveToThread is called
        #NOTE: Qt.QueuedConnection is important...
        self.worker = None
        self.worker = TransferWorker(dc)
        thread.started.connect(self.worker.start, Qt.QueuedConnection)
        self.worker.moveToThread(thread)
        self.worker.finished.connect(self._transferFinished, Qt.QueuedConnection)
        self.worker.finished.connect(self.worker.deleteLater, Qt.QueuedConnection)
        self.worker.finished.connect(thread.deleteLater, Qt.QueuedConnection)
        self.worker.progress.connect(self._transferProgress, Qt.QueuedConnection)
        self.worker.started.connect(self._transferStart, Qt.QueuedConnection)
        self.worker.status.connect(self._transferStatus, Qt.QueuedConnection)
        
        thread.start()
        
    @QtCore.Slot(str)
    def _transferStatus(self, msg):
        'Transfer Status Message'
        self._txtStatus.append(msg)
        
    @QtCore.Slot(int)
    def _transferStart(self, nBytes):
        'Transfer Thread Stated'
        if nBytes > 0:
            self._pbTransfer.setMaximum(nBytes)
        else:
            self._pbTransfer.setMaximum(100)
        self._pbTransfer.reset()
        
    @QtCore.Slot(int)
    def _transferProgress(self, nTransferred):
        'Transfer Thread Progress Event'
        self._pbTransfer.setValue(nTransferred)
        
    @QtCore.Slot(models.Dive)
    def _transferParsed(self, dive):
        'Transfer Thread Parsed Dive'
        self._logbook.session.add(dive)
        
    @QtCore.Slot()
    def _transferFinished(self):
        'Transfer Thread Finished'
        self._logbook.session.commit()
        
        self._txtLogbook.setEnabled(True)
        self._btnBrowse.setEnabled(True)
        self._cbxComputer.setEnabled(True)
        self._btnAddComputer.setEnabled(True)
        self._btnRemoveComputer.setEnabled(True)
        self._btnTransfer.setEnabled(True)
        self._btnExit.setEnabled(True)