def __init__(self): QWidget.__init__(self) self.ui = Ui_InstallWidget() self.ui.setupUi(self) self.installProgress = InstallProgressWidget(self) self.timer = QTimer(self) QObject.connect(self.timer, SIGNAL("timeout()"), self.changeSlideshows) self.poll_timer = QTimer(self) QObject.connect(self.poll_timer, SIGNAL("timeout()"), self.checkQueueEvent) if ctx.consts.lang == "tr": self.installProgress.ui.progress.setFormat("%%p") self.iter_slideshows = iter_slideshows() # show first pic self.changeSlideshows() self.total = 0 self.cur = 0 self.has_errors = False # mutual exclusion self.mutex = None self.wait_condition = None self.queue = None self.retry_answer = False self.sys_copier = None
def __init__(self, parent=None): super(DiagnosticExplain, self).__init__(parent) self.setupUi(self) QObject.connect(self.dont_show_again_chk_box, SIGNAL("stateChanged(int)"), lambda: self.parent().parent().update_user_prefs("explain_diag", \ not self.dont_show_again_chk_box.isChecked()))
def _createImageController(self, image, name, basename, model=False, save=False): dprint(2, "creating ImageController for", name) ic = ImageController(image, self, self, name, save=save) ic.setNumber(len(self._imagecons)) self._imagecons.insert(0, ic) self._imagecon_loadorder.append(ic) if model: self._model_imagecons.add(id(ic)) self._lo.addWidget(ic) if self._border_pen: ic.addPlotBorder(self._border_pen, basename, self._label_color, self._label_bg_brush) # attach appropriate signals image.connect(SIGNAL("slice"), self.fastReplot) image.connect(SIGNAL("repaint"), self.replot) image.connect(SIGNAL("raise"), self._currier.curry(self.raiseImage, ic)) image.connect(SIGNAL("unload"), self._currier.curry(self.unloadImage, ic)) image.connect(SIGNAL("center"), self._currier.curry(self.centerImage, ic)) QObject.connect(ic.renderControl(), SIGNAL("displayRangeChanged"), self._currier.curry(self._updateDisplayRange, ic.renderControl())) QObject.connect(ic.renderControl(), SIGNAL("displayRangeLocked"), self._currier.curry(self._lockDisplayRange, ic.renderControl())) self._plot = None # add to menus dprint(2, "repopulating menus") self._repopulateMenu() # center and raise to top of stack self.raiseImage(ic) if not self._center_image: self.centerImage(ic, emit=False) else: ic.setPlotProjection(self._center_image.projection) # signal self.emit(SIGNAL("imagesChanged")) return ic
def _exportImageToPNG(self, filename=None): if not filename: if not self._export_png_dialog: dialog = self._export_png_dialog = QFileDialog(self, "Export image to PNG", ".", "*.png") dialog.setDefaultSuffix("png") dialog.setFileMode(QFileDialog.AnyFile) dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setModal(True) QObject.connect(dialog, SIGNAL("filesSelected(const QStringList &)"), self._exportImageToPNG) return self._export_png_dialog.exec_() == QDialog.Accepted busy = BusyIndicator() if isinstance(filename, QStringList): filename = filename[0] filename = str(filename) # make QPixmap nx, ny = self.image.imageDims() (l0, l1), (m0, m1) = self.image.getExtents() pixmap = QPixmap(nx, ny) painter = QPainter(pixmap) # use QwtPlot implementation of draw canvas, since we want to avoid caching xmap = QwtScaleMap() xmap.setPaintInterval(0, nx) xmap.setScaleInterval(l1, l0) ymap = QwtScaleMap() ymap.setPaintInterval(ny, 0) ymap.setScaleInterval(m0, m1) self.image.draw(painter, xmap, ymap, pixmap.rect()) painter.end() # save to file try: pixmap.save(filename, "PNG") except Exception as exc: self.emit(SIGNAL("showErrorMessage"), "Error writing %s: %s" % (filename, str(exc))) return self.emit(SIGNAL("showMessage"), "Exported image to file %s" % filename)
def __init__(self, parent, label, filename=None, dialog_label=None, file_types=None, default_suffix=None, file_mode=QFileDialog.AnyFile): QWidget.__init__(self, parent) lo = QHBoxLayout(self) lo.setContentsMargins(0, 0, 0, 0) lo.setSpacing(5) # label lab = QLabel(label, self) lo.addWidget(lab, 0) # text field self.wfname = QLineEdit(self) self.wfname.setReadOnly(True) self.setFilename(filename) lo.addWidget(self.wfname, 1) # selector wsel = QToolButton(self) wsel.setText("Choose...") QObject.connect(wsel, SIGNAL("clicked()"), self._chooseFile) lo.addWidget(wsel, 0) # other init self._file_dialog = None self._dialog_label = dialog_label or label self._file_types = file_types or "All files (*)" self._file_mode = file_mode self._default_suffix = default_suffix self._dir = None
def __init__(self, parent, isEdit): KDialog.__init__(self, parent) self.parent = parent self.isEdit = isEdit layout = QVBoxLayout(self.mainWidget()) informationBox = KButtonGroup(self) informationBox.setTitle("Server information") if self.isEdit: self.oldName = "" self.name = KLineEdit() QObject.connect(self.name, SIGNAL("editingFinished()"), self.nameFinished) self.hostIP = KLineEdit() self.port = KIntNumInput(22) self.login = KLineEdit() self.switches = KLineEdit() self.passCheckbox = QCheckBox("Password") QObject.connect(self.passCheckbox, SIGNAL("stateChanged(int)"), self.passwordChecked) self.keyCheckbox = QCheckBox("Private Key") QObject.connect(self.keyCheckbox, SIGNAL("stateChanged(int)"), self.keyChecked) self.password = KLineEdit() self.password.setPasswordMode(True) self.password.setEnabled(False) self.keyFilePath = KLineEdit() self.keyFilePath.setEnabled(False) self.browseButton = KPushButton("Browse") self.browseButton.setEnabled(False) QObject.connect(self.browseButton, SIGNAL("clicked()"), self.openFileDialog) informationBoxLayout = QGridLayout(informationBox) informationBoxLayout.addWidget(QLabel("Name:"), 0, 0) informationBoxLayout.addWidget(self.name, 0, 1) informationBoxLayout.addWidget(QLabel("Host/IP:"), 1, 0) informationBoxLayout.addWidget(self.hostIP, 1, 1) informationBoxLayout.addWidget(QLabel("Port:"), 2, 0) informationBoxLayout.addWidget(self.port, 2, 1) informationBoxLayout.addWidget(QLabel("Login:"******"SSH command line:"), 4, 0) informationBoxLayout.addWidget(self.switches, 4, 1) authenticationBox = KButtonGroup(self) authenticationBox.setTitle("Authentication") authenticationBoxLayout = QGridLayout(authenticationBox) authenticationBoxLayout.addWidget(self.passCheckbox, 0, 0) authenticationBoxLayout.addWidget(self.password, 0, 1) authenticationBoxLayout.addWidget(self.keyCheckbox, 1, 0) authenticationBoxLayout.addWidget(self.keyFilePath, 1, 1) authenticationBoxLayout.addWidget(self.browseButton, 1, 2) layout.addWidget(informationBox) layout.addWidget(authenticationBox) self.enableButtonOk(False) QObject.connect(self, SIGNAL("okClicked()"), self.saveSettings)
def __init__(self, *args): QWidget.__init__(self, *args) lo = QHBoxLayout(self) lo.setContentsMargins(0, 0, 0, 0) lo.setSpacing(5) # type selector self.wtypesel = QComboBox(self) for i, tp in enumerate(self.ValueTypes): self.wtypesel.addItem(tp.__name__) QObject.connect(self.wtypesel, SIGNAL("activated(int)"), self._selectTypeNum) typesel_lab = QLabel("&Type:", self) typesel_lab.setBuddy(self.wtypesel) lo.addWidget(typesel_lab, 0) lo.addWidget(self.wtypesel, 0) self.wvalue = QLineEdit(self) self.wvalue_lab = QLabel("&Value:", self) self.wvalue_lab.setBuddy(self.wvalue) self.wbool = QComboBox(self) self.wbool.addItems(["false", "true"]) self.wbool.setCurrentIndex(1) lo.addWidget(self.wvalue_lab, 0) lo.addWidget(self.wvalue, 1) lo.addWidget(self.wbool, 1) self.wvalue.hide() # make input validators self._validators = {int: QIntValidator(self), float: QDoubleValidator(self)} # select bool type initially self._selectTypeNum(0)
def __init__(self, parent_gb, object_name, rules, eligible_custom_fields, db): self.rules = rules self.eligible_custom_fields = eligible_custom_fields self.db = db QTableWidget.__init__(self) self.setObjectName(object_name) self.layout = parent_gb.layout() # Add ourselves to the layout sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) #sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(sizePolicy) self.setMaximumSize(QSize(16777215, self.MAXIMUM_TABLE_HEIGHT)) self.setColumnCount(0) self.setRowCount(0) self.layout.addWidget(self) self.last_row_selected = self.currentRow() self.last_rows_selected = self.selectionModel().selectedRows() self._init_controls() # Hook check_box changes QObject.connect(self, SIGNAL('cellChanged(int,int)'), self.enabled_state_changed)
def __init__(self, parent=None): QGLViewer.__init__(self, parent) self.bottomwidget = parent.bottomwidget self.__views = [] self.__currentview = None self.__initialview = None self.__aboutview = None self.setMouseTracking(True) self.backButton = GLButton(self, 20, 20, 48, 48, img=get_shared_image('previous.png'), action=self.setCurrentViewId, togglable=False, params=[self.__initialview]) self.activeWidgets = [self.backButton] self.focusWidget = None self.selectedWidget = None self.__initiated__ = False self.mouseinteraction = True self.viewInterpolator = KeyFrameInterpolator() self.viewInterpolator.setFrame(self.camera().frame()) QObject.connect(self.viewInterpolator, SIGNAL('interpolated()'), self.updateGL) QObject.connect(self.viewInterpolator, SIGNAL('endReached()'), self.endInterpolateView) self.__viewIter__ = iter(self.__views) self.__valueViewIter__ = None self.__first_initialization__ = True
def __init__(self, *args): QWidget.__init__(self, *args) lo = QHBoxLayout(self) lo.setContentsMargins(0, 0, 0, 0) lo.setSpacing(5) # type selector self.wtypesel = QComboBox(self) for i, tp in enumerate(self.ValueTypes): self.wtypesel.addItem(tp.__name__) QObject.connect(self.wtypesel, SIGNAL("activated(int)"), self._selectTypeNum) typesel_lab = QLabel("&Type:", self) typesel_lab.setBuddy(self.wtypesel) lo.addWidget(typesel_lab, 0) lo.addWidget(self.wtypesel, 0) self.wvalue = QLineEdit(self) self.wvalue_lab = QLabel("&Value:", self) self.wvalue_lab.setBuddy(self.wvalue) self.wbool = QComboBox(self) self.wbool.addItems(["false", "true"]) self.wbool.setCurrentIndex(1) lo.addWidget(self.wvalue_lab, 0) lo.addWidget(self.wvalue, 1) lo.addWidget(self.wbool, 1) self.wvalue.hide() # make input validators self._validators = { int: QIntValidator(self), float: QDoubleValidator(self) } # select bool type initially self._selectTypeNum(0)
def __init__(self, parent, config_name=None, buttons=[], *args): """Creates dialog. 'config_name' is used to get/set default window size from Config object 'buttons' can be a list of names or (QPixmapWrapper,name[,tooltip]) tuples to provide custom buttons at the bottom of the dialog. When a button is clicked, the dialog emits SIGNAL("name"). A "Close" button is always provided, this simply hides the dialog. """ QDialog.__init__(self, parent, *args) self.setModal(False) lo = QVBoxLayout(self) # create viewer self.label = QLabel(self) self.label.setMargin(5) self.label.setWordWrap(True) lo.addWidget(self.label) self.label.hide() self.viewer = QTextBrowser(self) lo.addWidget(self.viewer) # self.viewer.setReadOnly(True) self.viewer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) QObject.connect(self.viewer, SIGNAL("anchorClicked(const QUrl &)"), self._urlClicked) self._source = None lo.addSpacing(5) # create button bar btnfr = QFrame(self) btnfr.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) # btnfr.setMargin(5) lo.addWidget(btnfr) lo.addSpacing(5) btnfr_lo = QHBoxLayout(btnfr) btnfr_lo.setMargin(5) # add user buttons self._user_buttons = {} for name in buttons: if isinstance(name, str): btn = QPushButton(name, btnfr) elif isinstance(name, (list, tuple)): if len(name) < 3: pixmap, name = name tip = None else: pixmap, name, tip = name btn = QPushButton(pixmap.icon(), name, btnfr) if tip: btn.setToolTip(tip) self._user_buttons[name] = btn btn._clicked = Kittens.utils.curry(self.emit, SIGNAL(name)) self.connect(btn, SIGNAL("clicked()"), btn._clicked) btnfr_lo.addWidget(btn, 1) # add a Close button btnfr_lo.addStretch(100) closebtn = QPushButton(pixmaps.grey_round_cross.icon(), "Close", btnfr) self.connect(closebtn, SIGNAL("clicked()"), self.hide) btnfr_lo.addWidget(closebtn, 1) # resize selves self.config_name = config_name or "html-viewer" width = Config.getint('%s-width' % self.config_name, 512) height = Config.getint('%s-height' % self.config_name, 512) self.resize(QSize(width, height))
def init(self): self.layout = QHBoxLayout() self.serversList = KListWidget(self.parent) QObject.connect(self.serversList, SIGNAL("itemSelectionChanged()"), self.serverSelected) QObject.connect(self.serversList, SIGNAL("doubleClicked(QListWidgetItem*, const QPoint&)"), self.showEditDialog) self.refreshServersList() self.buttonsLayout = QVBoxLayout() self.buttonsLayout.setAlignment(Qt.AlignTop) self.addButton = KPushButton("Add") QObject.connect(self.addButton, SIGNAL("clicked()"), self.showAddDialog) self.editButton = KPushButton("Edit") self.editButton.setEnabled (False) QObject.connect(self.editButton, SIGNAL("clicked()"), self.showEditDialog) self.removeButton = KPushButton("Remove") self.removeButton.setEnabled (False) QObject.connect(self.removeButton, SIGNAL("clicked()"), self.removeServer) self.buttonsLayout.addWidget(self.addButton) self.buttonsLayout.addWidget(self.editButton) self.buttonsLayout.addWidget(self.removeButton) self.layout.addWidget(self.serversList) self.layout.addLayout(self.buttonsLayout) self.setLayout(self.layout)
def initialize(self): """Ninja-ide plugin initializer.""" self.editor_s = self.locator.get_service('editor') tab_manager = self.editor_s._main.actualTab self.completer = DocumentCompleter() # to-do: make these configurable settings self.completer.setCompletionMode(QtGui.QCompleter.PopupCompletion) self.completer.setCaseSensitivity(QtCore.Qt.CaseSensitive) # init current tabs, if any for i in xrange(tab_manager.count()): editor = tab_manager.widget(i) self._add_completer(editor) # set completer for current tab editor = self.editor_s.get_editor() if editor is not None: self.completer.setWidget(editor) # on file open, init completer self.editor_s.fileOpened.connect(self._set_completer_on_open) # on key press, check to show completer self.editor_s.editorKeyPressEvent.connect(self.key_press) # on tab change, update completer self.editor_s.currentTabChanged.connect(self._set_completer) QObject.connect(self.completer, QtCore.SIGNAL("activated(const QString&)"), self.insert_completion)
def addColumnCategory(self, name, columns, visible=True): qa = QAction(name, self) qa.setCheckable(True) qa.setChecked(visible) if not visible: self._showColumnCategory(columns, False) QObject.connect(qa, SIGNAL("toggled(bool)"), self._currier.curry(self._showColumnCategory, columns)) self._column_views.append((name, qa, columns))
def __init__(self, parent, flags=Qt.WindowFlags()): QDialog.__init__(self, parent, flags) self.setModal(False) self.setWindowTitle("Select sources by...") lo = QVBoxLayout(self) lo.setMargin(10) lo.setSpacing(5) # select by lo1 = QHBoxLayout() lo.addLayout(lo1) lo1.setContentsMargins(0, 0, 0, 0) # lab = QLabel("Select:") # lo1.addWidget(lab) self.wselby = QComboBox(self) lo1.addWidget(self.wselby, 0) QObject.connect(self.wselby, SIGNAL("activated(const QString &)"), self._setup_selection_by) # under/over self.wgele = QComboBox(self) lo1.addWidget(self.wgele, 0) self.wgele.addItems([">", ">=", "<=", "<", "sum<=", "sum>"]) QObject.connect(self.wgele, SIGNAL("activated(const QString &)"), self._select_threshold) # threshold value self.wthreshold = QLineEdit(self) QObject.connect(self.wthreshold, SIGNAL("editingFinished()"), self._select_threshold) lo1.addWidget(self.wthreshold, 1) # min and max label self.wminmax = QLabel(self) lo.addWidget(self.wminmax) # selection slider lo1 = QHBoxLayout() lo.addLayout(lo1) self.wpercent = QSlider(self) self.wpercent.setTracking(False) QObject.connect(self.wpercent, SIGNAL("valueChanged(int)"), self._select_percentile) QObject.connect(self.wpercent, SIGNAL("sliderMoved(int)"), self._select_percentile_threshold) self.wpercent.setRange(0, 100) self.wpercent.setOrientation(Qt.Horizontal) lo1.addWidget(self.wpercent) self.wpercent_lbl = QLabel("0%", self) self.wpercent_lbl.setMinimumWidth(64) lo1.addWidget(self.wpercent_lbl) # # hide button # lo.addSpacing(10) # lo2 = QHBoxLayout() # lo.addLayout(lo2) # lo2.setContentsMargins(0,0,0,0) # hidebtn = QPushButton("Close",self) # hidebtn.setMinimumWidth(128) # QObject.connect(hidebtn,SIGNAL("clicked()"),self.hide) # lo2.addStretch(1) # lo2.addWidget(hidebtn) # lo2.addStretch(1) # self.setMinimumWidth(384) self._in_select_threshold = False self._sort_index = None self.qerrmsg = QErrorMessage(self)
def show_source_selector(mainwin, model): dialog = getattr(mainwin, '_source_selector_dialog', None) if not dialog: dialog = mainwin._source_selector_dialog = SourceSelectorDialog(mainwin) QObject.connect(mainwin, SIGNAL("modelChanged"), dialog.setModel) QObject.connect(mainwin, SIGNAL("closing"), dialog.close) dialog.setModel(model) # show dialog dialog.show() dialog.raise_()
def _openFileCallback(self): if not self._open_file_dialog: filters = ";;".join( ["%s (%s)" % (name, " ".join(patterns)) for name, patterns, func in self._load_file_types]) dialog = self._open_file_dialog = QFileDialog(self, "Open sky model", ".", filters) dialog.setFileMode(QFileDialog.ExistingFile) dialog.setModal(True) QObject.connect(dialog, SIGNAL("filesSelected(const QStringList &)"), self.openFile) self._open_file_dialog.exec_() return
def initialize(self): """plugin initializer.""" self.completer = DocumentCompleter() self.completer.setCompletionMode(QCompleter.PopupCompletion) self.completer.setCaseSensitivity(Qt.CaseSensitive) self._add_completer(self.editor) self.completer.setWidget(self.editor) QObject.connect(self.completer, SIGNAL("activated(const QString&)"), self.insert_completion)
def loadImage(self, filename=None, duplicate=True, to_top=True, model=None): """Loads image. Returns ImageControlBar object. If image is already loaded: returns old ICB if duplicate=False (raises to top if to_top=True), or else makes a new control bar. If model is set to a source name, marks the image as associated with a model source. These can be unloaded en masse by calling unloadModelImages(). """ if filename is None: if not self._load_image_dialog: dialog = self._load_image_dialog = QFileDialog(self, "Load FITS image", ".", "FITS images (%s);;All files (*)" % (" ".join( ["*" + ext for ext in FITS_ExtensionList]))) dialog.setFileMode(QFileDialog.ExistingFile) dialog.setModal(True) QObject.connect(dialog, SIGNAL("filesSelected(const QStringList &)"), self.loadImage) self._load_image_dialog.exec_() return None if isinstance(filename, QStringList): filename = filename[0] filename = str(filename) # report error if image does not exist if not os.path.exists(filename): self.showErrorMessage("""FITS image %s does not exist.""" % filename) return None # see if image is already loaded if not duplicate: for ic in self._imagecons: if ic.getFilename() and os.path.samefile(filename, ic.getFilename()): if to_top: self.raiseImage(ic) if model: self._model_imagecons.add(id(ic)) return ic # load the FITS image busy = BusyIndicator() dprint(2, "reading FITS image", filename) self.showMessage("""Reading FITS image %s""" % filename, 3000) QApplication.flush() try: image = SkyImage.FITSImagePlotItem(str(filename)) except KeyboardInterrupt: raise except: busy = None traceback.print_exc() self.showErrorMessage("""<P>Error loading FITS image %s: %s. This may be due to a bug in Tigger; if the FITS file loads fine in another viewer, please send the FITS file, along with a copy of any error messages from the text console, to [email protected].</P>""" % ( filename, str(sys.exc_info()[1]))) return None # create control bar, add to widget stack ic = self._createImageController(image, "model source '%s'" % model if model else filename, model or image.name, model=model) self.showMessage("""Loaded FITS image %s""" % filename, 3000) dprint(2, "image loaded") return ic
def _chooseFile(self): if self._file_dialog is None: dialog = self._file_dialog = QFileDialog(self, self._dialog_label, ".", self._file_types) if self._default_suffix: dialog.setDefaultSuffix(self._default_suffix) dialog.setFileMode(self._file_mode) dialog.setModal(True) if self._dir is not None: dialog.setDirectory(self._dir) QObject.connect(dialog, SIGNAL("filesSelected(const QStringList &)"), self.setFilename) return self._file_dialog.exec_()
def __init__(self, *args): TigGUI.kitties.widgets.ClickableTreeWidget.__init__(self, *args) self._currier = PersistentCurrier() self.model = None # insert columns self.setHeaderLabels(ViewColumns) self.headerItem().setText(ColumnIapp, "I(app)") self.header().setMovable(False) self.header().setClickable(True) self.setSortingEnabled(True) self.setRootIsDecorated(False) self.setEditTriggers(QAbstractItemView.AllEditTriggers) self.setMouseTracking(True) # set column width modes for icol in range(NumColumns - 1): self.header().setResizeMode(icol, QHeaderView.ResizeToContents) self.header().setStretchLastSection(True) ## self.setTextAlignment(ColumnR,Qt.AlignRight) ## self.setTextAlignment(ColumnType,Qt.AlignHCenter) # _column_enabled[i] is True if column is available in the model. # _column_show[i] is True if column is currently being shown (via a view control) self._column_enabled = [True] * NumColumns self._column_shown = [True] * NumColumns # other listview init self.header().show() self.setSelectionMode(QTreeWidget.ExtendedSelection) self.setAllColumnsShowFocus(True) ## self.setShowToolTips(True) self._updating_selection = False self.setRootIsDecorated(False) # connect signals to track selected sources QObject.connect(self, SIGNAL("itemSelectionChanged()"), self._selectionChanged) QObject.connect(self, SIGNAL("itemEntered(QTreeWidgetItem*,int)"), self._itemHighlighted) # add "View" controls for different column categories self._column_views = [] self._column_widths = {} self.addColumnCategory("Position", [ColumnRa, ColumnDec]) self.addColumnCategory("Position errors", [ColumnRa_err, ColumnDec_err], False) self.addColumnCategory("Type", [ColumnType]) self.addColumnCategory("Flux", [ColumnIapp, ColumnI]) self.addColumnCategory("Flux errors", [ColumnI_err], False) self.addColumnCategory("Polarization", [ColumnQ, ColumnU, ColumnV, ColumnRm]) self.addColumnCategory( "Polarization errors", [ColumnQ_err, ColumnU_err, ColumnV_err, ColumnRm_err], False) self.addColumnCategory("Spectrum", [ColumnSpi]) self.addColumnCategory("Spectrum errors", [ColumnSpi_err], False) self.addColumnCategory("Shape", [ColumnShape]) self.addColumnCategory("Shape errors", [ColumnShape_err], False) self.addColumnCategory("Tags", [ColumnTags])
def __init__(self, parent=None): """Constructor.""" super(MainClassDialog, self).__init__(parent) # Set up the user interface from Designer. # After setupUI you can access any designer object by doing # self.<objectname>, and you can use autoconnect slots - see # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html # #widgets-and-dialogs-with-auto-connect self.setupUi(self) self.__layoutData = LayoutData() QObject.connect(self.btnLogoFilepicker, SIGNAL("clicked()"),self.pickLogoFile)
def show_source_selector(mainwin, model): dialog = getattr(mainwin, '_source_selector_dialog', None) if not dialog: dialog = mainwin._source_selector_dialog = SourceSelectorDialog( mainwin) QObject.connect(mainwin, SIGNAL("modelChanged"), dialog.setModel) QObject.connect(mainwin, SIGNAL("closing"), dialog.close) dialog.setModel(model) # show dialog dialog.show() dialog.raise_()
def __moduleCompleter(self): """ Auto completes module names in self.lookInsideEdit """ completer = TagsCompleter(self.lookInsideEdit, self.__listAllModules()) completer.setCaseSensitivity(Qt.CaseInsensitive) QObject.connect(self.lookInsideEdit, SIGNAL('text_changed(PyQt_PyObject, PyQt_PyObject)'), completer.update) QObject.connect(completer, SIGNAL('activated(QString)'), self.lookInsideEdit.complete_text) completer.setWidget(self.addPathEdit) completer.setWidget(self.lookInsideEdit)
def run_command(self, program, args): if debug_run(): print "will run this command:", program, args from PyQt4.Qt import QStringList, QProcess, QObject, SIGNAL, QDir # modified from runSim.py arguments = QStringList() if sys.platform == 'win32': program = "\"%s\"" % program # Double quotes needed by Windows. ###@@@ test this ### try it with blanks in output file name and in program name, once it works ###@@@ for arg in [program] + args: if arg: arguments.append(arg) self.simProcess = simProcess = QProcess() simProcess.setArguments(arguments) simProcess.setWorkingDirectory(QDir(self.working_directory)) # in case it writes random files if 1: # report stdout/stderr def blabout(): print "stdout:", simProcess.readStdout() ##e should also mention its existence in history, but don't copy it all there in case a lot def blaberr(): text = str(simProcess.readStderr()) # str since it's QString (i hope it can't be unicode) print "stderr:", text env.history.message(redmsg("%s stderr: " % self.plugin_name + quote_html(text))) # examples from CoNTub/bin/HJ: # stderr: BAD INPUT # stderr: Error: Indices of both tubes coincide QObject.connect(simProcess, SIGNAL("readyReadStdout()"), blabout) QObject.connect(simProcess, SIGNAL("readyReadStderr()"), blaberr) started = simProcess.start() ###k what is this code? i forget if true means ok or error if debug_run(): print "qprocess started:",started while 1: ###e need to make it abortable! from which abort button? ideally, one on the dialog; maybe cancel button?? # on exception: simProcess.kill() if simProcess.isRunning(): if debug_run(): print "still running" time.sleep(1) else: time.sleep(0.1) else: break if debug_run(): print "process done i guess: normalExit = %r, (if normal) exitStatus = %r" % \ (simProcess.normalExit(), simProcess.exitStatus()) if 1: QObject.disconnect(simProcess, SIGNAL("readyReadStdout()"), blabout) QObject.disconnect(simProcess, SIGNAL("readyReadStderr()"), blaberr) if simProcess.normalExit(): return simProcess.exitStatus() else: return -1
def makeControlWidgets(self, parent): """Creates control widgets for the colormap's internal parameters. "parent" is a parent widget. Returns None if no controls are required""" top = QWidget(parent) layout = QGridLayout(top) layout.setContentsMargins(0, 0, 0, 0) for irow, icol, control in ((0, 0, self.gamma), (0, 1, self.color), (1, 0, self.cycles), (1, 1, self.hue)): control.makeControlWidgets(top, layout, irow, icol) QObject.connect(control, SIGNAL("valueChanged"), self.emitChange) QObject.connect(control, SIGNAL("valueMoved"), self.emitPreview) return top
def prompt_metadata(controller, file_path): """Display a Qt web view to prompt about metadata.""" def close(): sys.exit() app = QtGui.QApplication(sys.argv) webview = MetadataWebView(controller, file_path) webview.resize(METADATA_WEBVIEW_WIDTH, METADATA_WEBVIEW_HEIGHT) webview.setWindowFlags(Qt.WindowStaysOnTopHint) QObject.connect(webview.page(), QtCore.SIGNAL("windowCloseRequested ()"), close) webview.show() sys.exit(app.exec_())
def __init__(self, title, widget=None, closeButton=True, keySequence=None, isDialog=False, icon=None): QDialog.__init__(self, ctx.mainScreen) self.setObjectName("dialog") self.isDialog = isDialog self.layout = QVBoxLayout() self.setLayout(self.layout) self.wlayout= QHBoxLayout() if icon: self.setStyleSheet("""QDialog QLabel{ margin-left:16px;margin-right:10px} QDialog#dialog {background-image:url(':/images/%s.png'); background-repeat:no-repeat; background-position: top left; padding-left:500px;} """ % icon) self.windowTitle = windowTitle(self, closeButton) self.setTitle(title) self.layout.setMargin(0) self.layout.addWidget(self.windowTitle) if widget: self.addWidget(widget) QObject.connect(widget, SIGNAL("finished(int)"), self.reject) QObject.connect(widget, SIGNAL("resizeDialog(int,int)"), self.resize) if closeButton: QObject.connect(self.windowTitle.pushButton, SIGNAL("clicked()"), self.reject) if keySequence: shortCut = QShortcut(keySequence, self) QObject.connect(shortCut, SIGNAL("activated()"), self.reject) QMetaObject.connectSlotsByName(self) self.resize(10,10)
def makeControlWidgets(self, parent, gridlayout, row, column): toprow = QWidget(parent) gridlayout.addWidget(toprow, row * 2, column) top_lo = QHBoxLayout(toprow) top_lo.setContentsMargins(0, 0, 0, 0) self._wlabel = QLabel(self.format % (self.name, self.value), toprow) top_lo.addWidget(self._wlabel) self._wreset = QToolButton(toprow) self._wreset.setText("reset") self._wreset.setToolButtonStyle(Qt.ToolButtonTextOnly) self._wreset.setAutoRaise(True) self._wreset.setEnabled(self.value != self._default) QObject.connect(self._wreset, SIGNAL("clicked()"), self._resetValue) top_lo.addWidget(self._wreset) self._wslider = QwtSlider(parent) # This works around a stupid bug in QwtSliders -- see comments on histogram zoom wheel above self._wslider_timer = QTimer(parent) self._wslider_timer.setSingleShot(True) self._wslider_timer.setInterval(500) QObject.connect(self._wslider_timer, SIGNAL("timeout()"), self.setValue) gridlayout.addWidget(self._wslider, row * 2 + 1, column) self._wslider.setRange(self.minval, self.maxval) self._wslider.setStep(self.step) self._wslider.setValue(self.value) self._wslider.setTracking(False) QObject.connect(self._wslider, SIGNAL("valueChanged(double)"), self.setValue) QObject.connect(self._wslider, SIGNAL("sliderMoved(double)"), self._previewValue)
def __init__(self, *args): Kittens.widgets.ClickableListWidget.__init__(self, *args) # insert columns, and numbers for them # setup other properties of the listview self.setAcceptDrops(True) self.setSelectionMode(QListWidget.SingleSelection) self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Minimum) QObject.connect(self, SIGNAL("itemSelectionChanged()"), self._selectionChanged) QObject.connect(self, SIGNAL("itemChanged(QListWidgetItem *)"), self._itemChanged) self._items = {} self._item_height = None self._max_height_items = 5 self._min_height = 8 self.setMaximumSize(1000000, self._min_height)
def generateServerList(self): menu = QMenu() self.actionGroup = QActionGroup(self) QObject.connect(self.actionGroup, SIGNAL("triggered(QAction*)"), self.openSubMenu) slist = self.servers.keys() slist.sort() for s in slist: server = self.servers[s] action = QAction(server.name, self) action.setData(server.name) menu.addAction(action) self.actionGroup.addAction(action) return menu
def makeButton(self, label, callback=None, width=None, icon=None): btn = QToolButton(self) # btn.setAutoRaise(True) label and btn.setText(label) icon and btn.setIcon(icon) # btn = QPushButton(label,self) # btn.setFlat(True) if width: btn.setMinimumWidth(width) btn.setMaximumWidth(width) if icon: btn.setIcon(icon) if callback: QObject.connect(btn, SIGNAL("clicked()"), callback) return btn
def __init__(self, *args): TigGUI.kitties.widgets.ClickableTreeWidget.__init__(self, *args) self._currier = PersistentCurrier() self.model = None # insert columns self.setHeaderLabels(ViewColumns) self.headerItem().setText(ColumnIapp, "I(app)") self.header().setMovable(False) self.header().setClickable(True) self.setSortingEnabled(True) self.setRootIsDecorated(False) self.setEditTriggers(QAbstractItemView.AllEditTriggers) self.setMouseTracking(True) # set column width modes for icol in range(NumColumns - 1): self.header().setResizeMode(icol, QHeaderView.ResizeToContents) self.header().setStretchLastSection(True) ## self.setTextAlignment(ColumnR,Qt.AlignRight) ## self.setTextAlignment(ColumnType,Qt.AlignHCenter) # _column_enabled[i] is True if column is available in the model. # _column_show[i] is True if column is currently being shown (via a view control) self._column_enabled = [True] * NumColumns self._column_shown = [True] * NumColumns # other listview init self.header().show() self.setSelectionMode(QTreeWidget.ExtendedSelection) self.setAllColumnsShowFocus(True) ## self.setShowToolTips(True) self._updating_selection = False self.setRootIsDecorated(False) # connect signals to track selected sources QObject.connect(self, SIGNAL("itemSelectionChanged()"), self._selectionChanged) QObject.connect(self, SIGNAL("itemEntered(QTreeWidgetItem*,int)"), self._itemHighlighted) # add "View" controls for different column categories self._column_views = [] self._column_widths = {} self.addColumnCategory("Position", [ColumnRa, ColumnDec]) self.addColumnCategory("Position errors", [ColumnRa_err, ColumnDec_err], False) self.addColumnCategory("Type", [ColumnType]) self.addColumnCategory("Flux", [ColumnIapp, ColumnI]) self.addColumnCategory("Flux errors", [ColumnI_err], False) self.addColumnCategory("Polarization", [ColumnQ, ColumnU, ColumnV, ColumnRm]) self.addColumnCategory("Polarization errors", [ColumnQ_err, ColumnU_err, ColumnV_err, ColumnRm_err], False) self.addColumnCategory("Spectrum", [ColumnSpi]) self.addColumnCategory("Spectrum errors", [ColumnSpi_err], False) self.addColumnCategory("Shape", [ColumnShape]) self.addColumnCategory("Shape errors", [ColumnShape_err], False) self.addColumnCategory("Tags", [ColumnTags])
def lineage(widget, die = True, depth = 0): """ Trace the parental lineage of a Qt 4 widget: parent, grandparent... This is helpful in diagnosing "RuntimeError: underlying C/C++ object has been deleted" errors. It is frequently wise to kill the program at the first such deletion, so that is the default behavior (switchable with die = False). """ if widget is not None: from PyQt4.Qt import QObject, SIGNAL print (depth * ' ') + repr(widget) def destruction(ignore, die = die, message = repr(widget) + " was just destroyed"): qt4here(message, show_traceback = True) if die: sys.exit(1) QObject.connect(widget, SIGNAL("destroyed(QObject *)"), destruction) lineage(widget.parent(), die, depth + 1)
def _createImageController(self, image, name, basename, model=False, save=False): dprint(2, "creating ImageController for", name) ic = ImageController(image, self, self, name, save=save) ic.setNumber(len(self._imagecons)) self._imagecons.insert(0, ic) self._imagecon_loadorder.append(ic) if model: self._model_imagecons.add(id(ic)) self._lo.addWidget(ic) if self._border_pen: ic.addPlotBorder(self._border_pen, basename, self._label_color, self._label_bg_brush) # attach appropriate signals image.connect(SIGNAL("slice"), self.fastReplot) image.connect(SIGNAL("repaint"), self.replot) image.connect(SIGNAL("raise"), self._currier.curry(self.raiseImage, ic)) image.connect(SIGNAL("unload"), self._currier.curry(self.unloadImage, ic)) image.connect(SIGNAL("center"), self._currier.curry(self.centerImage, ic)) QObject.connect( ic.renderControl(), SIGNAL("displayRangeChanged"), self._currier.curry(self._updateDisplayRange, ic.renderControl())) QObject.connect( ic.renderControl(), SIGNAL("displayRangeLocked"), self._currier.curry(self._lockDisplayRange, ic.renderControl())) self._plot = None # add to menus dprint(2, "repopulating menus") self._repopulateMenu() # center and raise to top of stack self.raiseImage(ic) if not self._center_image: self.centerImage(ic, emit=False) else: ic.setPlotProjection(self._center_image.projection) # signal self.emit(SIGNAL("imagesChanged")) return ic
def saveFileAs(self, filename=None): """Saves file using the specified 'filename'. If filename is None, opens dialog to get a filename. Returns True if saving succeeded, False on error (or if cancelled by user). """ if filename is None: if not self._save_as_dialog: filters = ";;".join( ["%s (%s)" % (name, " ".join(patterns)) for name, patterns, func in self._save_file_types]) dialog = self._save_as_dialog = QFileDialog(self, "Save sky model", ".", filters) dialog.setDefaultSuffix(ModelHTML.DefaultExtension) dialog.setFileMode(QFileDialog.AnyFile) dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setConfirmOverwrite(False) dialog.setModal(True) QObject.connect(dialog, SIGNAL("filesSelected(const QStringList &)"), self.saveFileAs) return self._save_as_dialog.exec_() == QDialog.Accepted # filename supplied, so save return self.saveFile(filename, confirm=False)
def __init__(self, parent, *args): QWidget.__init__(self, parent, *args) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) lo = QVBoxLayout(self) lo.setContentsMargins(0, 0, 0, 0) lo1 = QHBoxLayout() lo.addLayout(lo1) lo1.setContentsMargins(0, 0, 0, 0) lbl = QLabel(QString("<nobr><b>Source groupings:</b></nobr>"), self) lo1.addWidget(lbl, 0) lo1.addStretch(1) # add show/hide button self._showattrbtn = QPushButton(self) self._showattrbtn.setMinimumWidth(256) lo1.addWidget(self._showattrbtn, 0) lo1.addStretch() QObject.connect(self._showattrbtn, SIGNAL("clicked()"), self._togglePlotControlsVisibility) # add table self.table = QTableWidget(self) lo.addWidget(self.table) QObject.connect(self.table, SIGNAL("cellChanged(int,int)"), self._valueChanged) self.table.setSelectionMode(QTableWidget.NoSelection) # setup basic columns self.table.setColumnCount(6 + len(self.EditableAttrs)) for i, label in enumerate( ("grouping", "total", "selection", "list", "plot", "style")): self.table.setHorizontalHeaderItem(i, QTableWidgetItem(label)) self.table.horizontalHeader().setSectionHidden(self.ColApply, True) # setup columns for editable grouping attributes for i, attr in self.AttrByCol.items(): self.table.setHorizontalHeaderItem( i, QTableWidgetItem(PlotStyles.StyleAttributeLabels[attr])) self.table.horizontalHeader().setSectionHidden(i, True) self.table.verticalHeader().hide() # other internal init self._attrs_shown = False self._togglePlotControlsVisibility() self.model = None self._setting_model = False self._currier = PersistentCurrier() # row of 'selected' grouping self._irow_selgroup = 0
def main(): app = QApplication(sys.argv) editor = CompleterLineEdit() completer = TagsCompleter(editor, TAGS) completer.setCaseSensitivity(Qt.CaseInsensitive) QObject.connect(editor, SIGNAL('text_changed(PyQt_PyObject, PyQt_PyObject)'), completer.update) QObject.connect(completer, SIGNAL('activated(QString)'), editor.complete_text) completer.setWidget(editor) editor.show() return app.exec_()
def qt4warnDestruction(obj, name = ''): message = '* * * * ' try: raise Exception except: f = sys.exc_info()[2].tb_frame f = f.f_back message += f.f_code.co_filename + (':%d' % f.f_lineno) if name: message += ' ' + name if debug_prefs.debug_pref("Enable QT4 WARNING messages", debug_prefs.Choice_boolean_False, prefs_key = True): print 'Setting up destruction warning', message def destruction(ignore, message = message): print 'OBJECT DESTROYED (exiting)', message #bruce 070521 revised message sys.exit(1) from PyQt4.Qt import QObject, SIGNAL QObject.connect(obj, SIGNAL("destroyed(QObject *)"), destruction)
def saveSelectionAs(self, filename=None, force=False): if not self.model: return if filename is None: if not self._save_sel_as_dialog: filters = ";;".join( ["%s (%s)" % (name, " ".join(patterns)) for name, patterns, func in self._save_file_types]) dialog = self._save_sel_as_dialog = QFileDialog(self, "Save sky model", ".", filters) dialog.setDefaultSuffix(ModelHTML.DefaultExtension) dialog.setFileMode(QFileDialog.AnyFile) dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setConfirmOverwrite(True) dialog.setModal(True) QObject.connect(dialog, SIGNAL("filesSelected(const QStringList &)"), self.saveSelectionAs) return self._save_sel_as_dialog.exec_() == QDialog.Accepted # save selection if isinstance(filename, QStringList): filename = filename[0] filename = str(filename) selmodel = self.model.copy() sources = [src for src in self.model.sources if src.selected] if not sources: self.showErrorMessage("""You have not selected any sources to save.""") return # try to determine the file type filetype, import_func, export_func, doc = Tigger.Models.Formats.resolveFormat(filename, None) if export_func is None: self.showErrorMessage("""Error saving model file %s: unsupported output format""" % filename) return busy = BusyIndicator() try: export_func(self.model, filename, sources=sources) except: busy = None self.showErrorMessage( """Error saving selection to model file %s: %s""" % (filename, str(sys.exc_info()[1]))) return False self.showMessage("""Wrote %d selected source%s to file %s""" % ( len(selmodel.sources), "" if len(selmodel.sources) == 1 else "s", filename), 3000) pass
def __init__(self, parent, modal=True, flags=Qt.WindowFlags(), caption="Select Tags", ok_button="Select"): QDialog.__init__(self, parent, flags) self.setModal(modal) self.setWindowTitle(caption) lo = QVBoxLayout(self) lo.setMargin(10) lo.setSpacing(5) # tag selector self.wtagsel = QListWidget(self) lo.addWidget(self.wtagsel) # self.wtagsel.setColumnMode(QListBox.FitToWidth) self.wtagsel.setSelectionMode(QListWidget.MultiSelection) QObject.connect(self.wtagsel, SIGNAL("itemSelectionChanged()"), self._check_tag) # buttons lo.addSpacing(10) lo2 = QHBoxLayout() lo.addLayout(lo2) lo2.setContentsMargins(0, 0, 0, 0) lo2.setMargin(5) self.wokbtn = QPushButton(ok_button, self) self.wokbtn.setMinimumWidth(128) QObject.connect(self.wokbtn, SIGNAL("clicked()"), self.accept) self.wokbtn.setEnabled(False) cancelbtn = QPushButton("Cancel", self) cancelbtn.setMinimumWidth(128) QObject.connect(cancelbtn, SIGNAL("clicked()"), self.reject) lo2.addWidget(self.wokbtn) lo2.addStretch(1) lo2.addWidget(cancelbtn) self.setMinimumWidth(384) self._tagnames = []
def __init__(self, *args): QWidget.__init__(self, *args) # init layout self._lo = QVBoxLayout(self) self._lo.setContentsMargins(0, 0, 0, 0) self._lo.setSpacing(0) # init internal state self._currier = PersistentCurrier() self._z0 = 0 # z-depth of first image, the rest count down from it self._updating_imap = False self._locked_display_range = False self._imagecons = [] self._imagecon_loadorder = [] self._center_image = None self._plot = None self._border_pen = None self._drawing_key = None self._load_image_dialog = None self._model_imagecons = set() # init menu and standard actions self._menu = QMenu("&Image", self) qag = QActionGroup(self) # exclusive controls for plotting topmost or all images self._qa_plot_top = qag.addAction("Display topmost image only") self._qa_plot_all = qag.addAction("Display all images") self._qa_plot_top.setCheckable(True) self._qa_plot_all.setCheckable(True) self._qa_plot_top.setChecked(True) QObject.connect(self._qa_plot_all, SIGNAL("toggled(bool)"), self._displayAllImages) self._closing = False self._qa_load_clipboard = None self._clipboard_mode = QClipboard.Clipboard QObject.connect(QApplication.clipboard(), SIGNAL("changed(QClipboard::Mode)"), self._checkClipboardPath) # populate the menu self._repopulateMenu()
def __init__(self, img_params_path, png_path, qpixmap_item, parent=None): super(EditPlotWindow, self).__init__(parent) self.setupUi(self) # img_params is a string that is the variable # name for the R object self.img_params_path = img_params_path print "parameters: %s" % self.img_params_path # if we're unable to load the required R data files, # e.g., because they were moved or deleted, then fail self.params_d = meta_py_r.load_vars_for_plot(self.img_params_path, \ return_params_dict=True) if not self.params_d: print "can't load R data for plot editing!" return None # @TODO reflect current params in UI at launch #self.populate_params() self.set_ui_values() # this is the QPixMap object that houses the # plot image self.pixmap_item = qpixmap_item self.png_path = png_path # the handle to the window in which # the image is being displayed self.results_window = parent self.current_param_vals = {} # get the button object self.apply_button = self.buttonBox.button(QDialogButtonBox.Apply) QObject.connect(self.apply_button, SIGNAL("clicked()"), self.regenerate_graph) self.populate_params()
def __init__(self, *args): QTreeWidget.__init__(self, *args) self.setContextMenuPolicy(Qt.CustomContextMenu) QObject.connect(self, SIGNAL('customContextMenuRequested(const QPoint &)'), self._request_context_menu) QObject.connect(self, SIGNAL('itemExpanded(QTreeWidgetItem *)'), self._item_expanded_collapsed) QObject.connect(self, SIGNAL('itemCollapsed(QTreeWidgetItem *)'), self._item_expanded_collapsed)
def __init__(self, title, widget=None, closeButton=True, keySequence=None, isDialog=False, icon=None): QDialog.__init__(self, ctx.mainScreen) self.setObjectName("dialog") self.isDialog = isDialog self.layout = QVBoxLayout() self.setLayout(self.layout) self.wlayout = QHBoxLayout() if icon: self.setStyleSheet( """QDialog QLabel{ margin-left:16px;margin-right:10px} QDialog#dialog {background-image:url(':/images/%s.png'); background-repeat:no-repeat; background-position: top left; padding-left:500px;} """ % icon) self.windowTitle = windowTitle(self, closeButton) self.setTitle(title) self.layout.setMargin(0) self.layout.addWidget(self.windowTitle) if widget: self.addWidget(widget) QObject.connect(widget, SIGNAL("finished(int)"), self.reject) QObject.connect(widget, SIGNAL("resizeDialog(int,int)"), self.resize) if closeButton: QObject.connect(self.windowTitle.pushButton, SIGNAL("clicked()"), self.reject) if keySequence: shortCut = QShortcut(keySequence, self) QObject.connect(shortCut, SIGNAL("activated()"), self.reject) QMetaObject.connectSlotsByName(self) self.resize(10, 10)
def __init__(self, parent, modal=True, flags=Qt.WindowFlags()): QDialog.__init__(self, parent, flags) self.setModal(modal) self.setWindowTitle("Add Tag") lo = QVBoxLayout(self) lo.setMargin(10) lo.setSpacing(5) # tag selector lo1 = QHBoxLayout() lo.addLayout(lo1) lo1.setSpacing(5) self.wtagsel = QComboBox(self) self.wtagsel.setEditable(True) wtagsel_lbl = QLabel("&Tag:", self) wtagsel_lbl.setBuddy(self.wtagsel) lo1.addWidget(wtagsel_lbl, 0) lo1.addWidget(self.wtagsel, 1) QObject.connect(self.wtagsel, SIGNAL("activated(int)"), self._check_tag) QObject.connect(self.wtagsel, SIGNAL("editTextChanged(const QString &)"), self._check_tag_text) # value editor self.valedit = ValueTypeEditor(self) lo.addWidget(self.valedit) # buttons lo.addSpacing(10) lo2 = QHBoxLayout() lo.addLayout(lo2) lo2.setContentsMargins(0, 0, 0, 0) lo2.setMargin(5) self.wokbtn = QPushButton("OK", self) self.wokbtn.setMinimumWidth(128) QObject.connect(self.wokbtn, SIGNAL("clicked()"), self.accept) self.wokbtn.setEnabled(False) cancelbtn = QPushButton("Cancel", self) cancelbtn.setMinimumWidth(128) QObject.connect(cancelbtn, SIGNAL("clicked()"), self.reject) lo2.addWidget(self.wokbtn) lo2.addStretch(1) lo2.addWidget(cancelbtn) self.setMinimumWidth(384)