1

I've been going around in circles with this for a few hours so hopefully someone can help. I am familiar with VB, C# but not Python - and struggling to do something fairly simple.

I have created a form using QT Designer. On this form are a QlistView widget and a "Browse..." button. I want to be able to select files by clicking on the button, and list these in the QlistView. Should be easy enough.

In languages I am familiar with I would reference the QlistView object using syntax like [form name].[control name] but cannot do that here, apparently.

I have got self.dlg set to the form itself.

The list widget is a QlistWidget, with the name listWidget.

I am using the following code to handle the button click:

def handleBrowseButton(self):
pth =os.path.normpath('E:')
filter = "TXT (*.txt)"
file_name = QtGui.QFileDialog()
file_name.setFileMode(3) # 3=existing files
names = file_name.getOpenFileNames(None, "Open files", pth, filter)
if not names:
  print "CANCELLED"
  return

l = self.dlg.findChild(listWidget)

...but getting a bit stuck at the last bit. Do I have to use findChild / findChildren / something else??

The above code does run, so I haven't got a problem getting to that point. The issue is just how to set a reference to the listWidget object on the form in order to refer to it from that point on.

My intention is to set 'l' to refer to the listWidget and then do something like

l.list.additem(filename)

closed as off-topic by Germán Carrillo, Fezter Oct 24 '16 at 2:08

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

  • From further experimentation I find that I can refer directly to other controls on the form. For instance these set usable references to a button and a container respectively: "f = self.dlg.cmdOK", e = self.dlg.gbSourceFiles. – wotnot Oct 23 '16 at 16:46
  • I think you can set the names of things in the QtDesigner to more meaningful names than the defaults. – Spacedman Oct 23 '16 at 17:14
2

I've got it, after lots of trial and error. Not sure what I was doing wrong originally, really. Must have been missing something, somewhere.

Controls can indeed be referenced using the normal 'dot' notation i.e.

def handleBrowseButton(self):
pth =os.path.normpath('E:')
filter = "TXT (*.txt)"
file_name = QtGui.QFileDialog()
file_name.setFileMode(3) # 3=existing files
names = file_name.getOpenFileNames(None, "Open files", pth, filter)
if not names:
  print "CANCELLED"
  return

self.dlg.listWidget.clear()

for fn in names:
  self.dlg.listWidget.addItem(fn)

Not the answer you're looking for? Browse other questions tagged or ask your own question.