def testPropertyValues(self): app = QApplication(sys.argv) textEdit = QPlainTextEdit() textEdit.insertPlainText("PySide INdT") selection = QTextEdit.ExtraSelection() selection.cursor = textEdit.textCursor() selection.cursor.setPosition(2) self.assertEqual(selection.cursor.position(), 2)
class ChatWidget(QWidget): """ A chatting widget. """ #: A notification (not chat!) message for the user message = Signal(str) def __init__(self, parent=None): QWidget.__init__(self, parent) self.setLayout(QVBoxLayout(self)) self.text_display = QPlainTextEdit(self) self.text_display.setReadOnly(True) self.layout().addWidget(self.text_display) self.text_input = QLineEdit(self) self.text_input.returnPressed.connect(self.send_text) self.layout().addWidget(self.text_input) QWidget.setTabOrder(self.text_input, self.text_display) self.setEnabled(False) self.message.emit('Not connected') self._connection = None @property def connected(self): """ ``True``, if this chat widget is connected to some server, ``False`` otherwise """ return (self._connection and self._connection.state() == QTcpSocket.ConnectedState) @property def connection(self): """ The connection used by this widget. """ return self._connection @connection.setter def connection(self, connection): self._connection = connection if not self.connected: # wait for connection, if the connection isn't available yet self._connection.connected.connect(self._enable_chat) else: self._enable_chat() # handle errors, disconnects and incoming data self._connection.error.connect(self._handle_error) self._connection.disconnected.connect(self._handle_disconnect) self._connection.readyRead.connect(self._receive_text) def _enable_chat(self): """ Enable the chat widget for chatting. """ self.message.emit('connected') self.setEnabled(True) # remove all text from the previous connection self.text_display.clear() def _handle_disconnect(self): """ Handle a disconnect. """ self.message.emit('disconnected') # disable the user interface self.setEnabled(False) # and disconnect from all slots and eventually delete the connection # itself self._connection.readyRead.disconnect(self._receive_text) self._connection.deleteLater() self._connection = None def _handle_error(self): self.message.emit(self._connection.errorString()) def _receive_text(self): text = _stream_for_connection(self.connection).readAll() self.text_display.insertPlainText('{0}'.format(text)) def send_text(self, text=None): """ Send ``text`` over the connection of this widget. Does nothing, if the widget is not connected. If ``text`` is ``None`` (the default), use the current input form the user. """ if self.connected: stream = _stream_for_connection(self.connection) if not text: text = self.text_input.text() self.text_input.clear() stream << text