widgets = {
'img':forms.ImageInput(attrs={'class':'box'}),
'title':forms.TextInput(attrs={'class':'box'}),
'title':forms.TextInput(attrs={'class':'box'}),
'title':forms.TextInput(attrs={'class':'box'}),
}
'img':forms.ImageInput(attrs={'class':'box'}), this line gives me error.
The widget for ImageField is FileInput not ImageInput, django has no widget called ImageInput...
Try this code
'img':forms.FileInput(attrs={'class': 'box'}),
Related
I want to display my C++ class as a ListView in QML. I have an empty vector, which will later be filled:
QList<QObject*> _myList;
and set the context
QQmlContext *ctxt = _eng->rootContext();
ctxt->setContextProperty("modelName",QVariant::fromValue(_myList));
In the qml file I have
ListView {
id: listView
model: modelName
delegate: myDelegate {}
}
But when starting the application I get the following error
qrc:/screen2.qml:252: ReferenceError: modelName is not defined
What am I doing wrong? Strangly, the error does not prevent the list from being correctly displayed once it is filled.
Call setContextProperty before loading your QML file.
When you load your QML file, the engine evaluates its bindings, since you haven't yet set the context property for modelName, it outputs a warning.
When you set it afterwards, this binding is reevaluated and that's why the list is eventually correctly displayed in your case.
I am trying to create a custom Gtk text entry. The basic idea is to put a button inside of a text entry. Here is a shortened version of my full code:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
builder = Gtk.Builder()
button = Gtk.Button('button')
entry = Gtk.Entry()
entry.add_child(builder, button, "button")
The button does not get shown and it fails with the error:
(pygtk_foobar.py:26622): Gtk-CRITICAL **: gtk_buildable_add_child:
assertion 'iface->add_child != NULL' failed
Any suggestions?
A GtkEntry widget is not a GtkContainer, and thus it cannot have child widgets added or removed to it.
Only widgets that inherit from the GtkContainer class can have children in GTK+.
If you want to put a button next to a text entry, you should pack both widgets into a container like GtkBox, e.g.:
box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=2)
entry = Gtk.Entry()
button = Gtk.Button(label='button', hexpand=True)
box.add(entry)
box.add(button)
box.show_all()
This will create a box with an entry and a button.
I'm using PyQt4 and python 2.7.9. I have a QTreeView that contains data from Oracle database. the code is this:
model = QStandardItemModel(0,1)
self.treeMedia.setModel(model)
for rowalb in self.SELECT_TREE_ALBUM(codus):
nodeItem = QStandardItem(str(rowalb[1]).decode('utf-8'))
for rowph in self.SELECT_TREE_PHOTO(int(rowalb[0])):
childItem = QStandardItem(str(rowph[0]))
childItem.setEditable(False)
nodeItem.insertRows(0, [childItem])
nodeItem.setEditable(False)
model.appendRow(nodeItem)
model.setHorizontalHeaderLabels(['Data'])
The SELECT_TREE_ALBUM (codus is the id of the album's owner) and SELECT_TREE_PHOTO are the functions that return data from database.The rowalb 1 is the name of the album and rowalb[0] is the ID, the rowalb[0] is used to get photos of this album.The picture shows this view:
I want to get the childItem data (e.g. 1491475964461012, 1491475821127693, 1491475631127712, 1491475141127761 or 1480407552234520) using doubleclick event. I tried to put these code into the constructor:
self.treeMedia.doubleClicked.connect(self.treeMedia_doubleClicked)
and after that I added the function:
def treeMedia_doubleClicked(self,index):
item = self.treeMedia.model().item(index.row(),index.column())
strData = item.data(0).toPyObject()
#self.treeMedia.currentIndex()
print('' + str(strData))
but sometimes I see the nodeItem information (e.g. "terror" or "fotos de perfil") and other ones I get this error: "AttributeError: 'NoneType' object has no attribute 'data'".What could be the problem? is the problem in filling the qtreeview? or is the problem in double click event function when using the index? Please help me. Thanks in advance.
If anyone is looking for answer.
def treeMedia_doubleClicked(self,index):
item = self.treeView.selectedIndexes()[0]
print item.model().itemFromIndex(index).text()
I realize this is a bit out of context, but posting here for any other passerbys...
in pyside6 either of these work
def treeMedia_doubleClicked(self, index):
print(self.name_of_model.filePath(index))
or
def treeMedia_doubleClicked(self, index):
print(index.model().filePath(index))
I need to create a text input dialog with multiple lines. Is there any way to do this using QInputDialog?
If not, is the simplest recommendation to subclass QPlainTextEdit?
QInputDialog and more precisely getText work only with a QLineEdit.
Just implement a small dialog sublass which contains a QPlainTextEdit. Shouldn't be too much work. Not as fast as QInputDialog, but not too much effort either.
Update: since version Qt 5.2, QInputDialog has getMultiLineText.
I was able to do that using QInputDialog and setting QInputDialog::UsePlainTextEditForTextInput.
However, one issue that I found was that QInputDialog was always selecting the text in the dialog (in exec()) and there is no flag to prevent that. The workaround was to connect the change in the selection to a lambda that deselects everything:
auto noteDialog = new QInputDialog(this);
noteDialog->setOptions(QInputDialog::UsePlainTextEditForTextInput);
noteDialog->setWindowTitle("Title");
noteDialog->setLabelText("Notes:");
noteDialog->setTextValue("text");
auto lineEdit = noteDialog->findChild<QPlainTextEdit*>();
connect(lineEdit, &QPlainTextEdit::selectionChanged, [lineEdit](){
if(lineEdit->textCursor().hasSelection())
{
QTextCursor cursor = lineEdit->textCursor();
cursor.clearSelection();
cursor.movePosition(QTextCursor::End);
lineEdit->setTextCursor(cursor);
}
});
bool ok = noteDialog->exec();
if (ok)
doSomething(noteDialog->textValue());
If you are fine with the selected text, QInputDialog::getMultiLineText alone should do the trick.
I needed this to work in Qt4 and this was one of the very few questions I found asking about it, none had any implementations as answers. I've just managed to replicate the functionality and look of Qt5 however, so even though it's in Python, I may as well post here as it could come in useful to others.
To get it working, it needed its own layout, and since QInputDialog builds the layout, QDialog had to be subclassed. I then added getMultiLineText to QInputDialog, which returns a reading from the QPlainTextEdit and the result of the new dialog.
class _QInputDialogMultiline(QDialog):
"""Build a replica interface of QInputDialog.getMultilineText."""
def __init__(self, parent, title, label, text='', **kwargs):
super(_QInputDialogMultiline, self).__init__(parent, **kwargs)
if title is not None:
self.setWindowTitle(title)
self.setLayout(QVBoxLayout())
self.layout().addWidget(QLabel(label))
self.textEdit = QPlainTextEdit()
self.layout().addWidget(self.textEdit)
buttonLayout = QHBoxLayout()
buttonLayout.addStretch()
okButton = QPushButton('OK')
buttonLayout.addWidget(okButton)
cancelButton = QPushButton('Cancel')
buttonLayout.addWidget(cancelButton)
self.layout().addLayout(buttonLayout)
self.textEdit.setPlainText(text)
self.textEdit.selectAll()
okButton.clicked.connect(self.accept)
cancelButton.clicked.connect(self.reject)
class QInputDialog(QInputDialog):
#classmethod
def getMultiLineText(cls, parent, title, label, text='', **kwargs):
dialog = _QInputDialogMultiline(parent, title, label, text, **kwargs)
result = dialog.exec_()
return (str(dialog.textEdit.toPlainText()), bool(result))
Example to show they look the same:
QInputDialog.getMultiLineText(None, 'Window Title', 'This is a label.', 'Initial text')
Qt4 (my code):
Qt5 (standard code):
To retrieve the user's input from QInputDialog::getText() into an expandable string:
bool ok;
std::string* comment = new std::string;
QString qComment = QInputDialog::getText(0,
"<title_of_input_dialog_displayed_at_top>",
"<label_of_input_field_displayed_at_left>",
QLineEdit::Normal, "<enter_this_or_that_here>", &ok);
if (ok && !qComment.isEmpty()) {
QByteArray qba = qComment.toLocal8Bit();
comment->assign(qba.data(), qba.size());
} else if (ok) { // user clicked Ok but did not enter text
comment->assign("<default_user_input>");
} else { // user clicked Cancel
...
}
delete comment;
I need to customize how the m2m widget for Django Admin gets displayed but I am kind of stumped where to start. I have tried subclassing couple of widgets from django.forms and django.contrib.admin.wigets but nothing seems to be working.
Here's a depiction of what I am looking for http://i.stack.imgur.com/81AY3.png.
Any help appreciated.
That looks like the kind of thing that could be achieved with JavaScript alone. For adding your own JavaScript to the Django admin, see the documentation for ModelAdmin media definitions.
This is what I came up with. It does most of the work. However, the list does not get updated when a new item is added and changing an item does not redirect back to the original page.
/your_app/forms.py
class ProductForm(forms.ModelForm):
class Media:
js = ('js/custom_m2m.js',)
class Meta:
model = Product
/your_media/js/custom_m2m.js
django.jQuery(function() {
var $ = django.jQuery;
// Add a new place holder div to hold the m2m list
$('div.options div').append('<div class="newdiv"></div>');
// Assign some variables
var target = "options"; // <-- Target Field
var newdiv = $('div.newdiv');
var next_page = window.location.pathname;
var add_link = $('div.'+target+' div a#add_id_'+target);
var edit_img = "/static/media_admin/img/admin/icon_changelink.gif";
var add_img = "/static/media_admin/img/admin/icon_addlink.gif";
// Make the placeholder div bit nicer
newdiv.attr("style", "line-height:20px; margin-left:105px;");
// Iterate through select options and append them to 'newdiv'
$('select#id_'+target+' option[selected="selected"]').each(function() {
newdiv.append(''+$(this).text()+' <img src="'+edit_img+'" /><br />');
});
// Add a 'Add new' link after the option list
add_link.html('<strong>Add new</strong> ' + add_link.html());
add_link.appendTo(newdiv);
// Show the 'newdiv' and hide the original dropdown
$('select#id_'+target).after(newdiv);
$('select#id_'+target).css("display", "none");
$('div.'+target+' p[class="help"]').css("display", "none");
});
As you can see, the above script uses some hardcoded paths. Any improvement would be helpful.