1.tableWidget怎么控制大小,能否用label来替代?
2.如何添加动作,点击目录后导出内容?
3.通过setColumnStretch
设置的列宽,在目录导出后,约束失效了,这是为什么?
import sys
from PyQt5.QtWidgets import *
import urllib.request as request
import Spider
class MainScene(QWidget):
def __init__(self):
super().__init__()
self.contextGrid()
self.show()
def contextGrid(self):
self.resize(500,300);
self.grid = QGridLayout()
self.setLayout(self.grid)
self.novelNameEdit = QLineEdit("http://xs.dmzj.com/2012/index.shtml")
self.searchBtn = QPushButton("Search")
self.blankLabel = QLabel("")
self.novelText = QLabel("Content")
self.grid.addWidget(self.novelNameEdit,0,0,1,1)
self.grid.addWidget(self.searchBtn,0,1,1,1)
self.grid.addWidget(self.blankLabel,0,2,1,3)
self.grid.addWidget(self.novelText,1,1,1,4)
self.grid.setColumnStretch(1,1)
self.grid.setColumnStretch(2,1)
self.grid.setColumnStretch(3,3)
self.searchBtn.clicked.connect(self.searchBtnClick)
def searchBtnClick (self):
pass
Sp = Spider.Catalogue()
content = request.urlopen(self.novelNameEdit.text()).read()
content = str(content, 'utf-8')
Sp.feed(content)
Sp.close()
catalogueCount = len(Sp.catalogueList)
tableWidget = QTableWidget(catalogueCount,1)
tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
for ca in range(catalogueCount):
tableWidget.setItem(ca,0,QTableWidgetItem(Sp.catalogueList[ca]))
self.grid.addWidget(tableWidget, 1, 0, 1, 1)
if __name__ == "__main__":
App = QApplication(sys.argv)
MS = MainScene()
sys.exit(App.exec_())
Spider.py
# -*- coding:utf-8 -*-
import html.parser as Pa
class Catalogue(Pa.HTMLParser):
a_t = False
alt = ""
title = ""
catalogueList = []
def handle_data(self, data):
if self.a_t is True:
self.catalogueList.append(data)
def handle_starttag(self, tag, attrs):
if str(tag).startswith("a"):
for key,value in attrs:
if key == "alt":
self.alt = value
elif key == "title":
self.title = value
elif key == "href" and (value.find("/2012/")) == 0 and (value.find("index.")) == -1 and (value.find(".txt")) == -1:
self.a_t = True
else:
self.a_t = False
def handle_endtag(self, tag):
if tag == "a":
self.a_t=False
class NovelText(Pa.HTMLParser):
a_t = False
def handle_starttag(self, tag, attrs):
if str(tag).startswith("p"):
for key,value in attrs:
if value == "novel_text":
self.a_t = True
break;
else:
self.a_t = False
def handle_data(self, data):
if self.a_t is True:
print(data)
1) 不能用label代替吧,畢竟不是一個東西
3) 見setColumnStretch說明
Sets the stretch factor of column column to stretch. The first column is number 0.
The stretch factor in relst column is number 0.
The stretch factor is relx . Columns with a higher stretch factor take more of the available space.
The default stretch factor is 0. If the stretch factor is 0 and no other column in this table can grow at all, the columncay stled the columige groge lrow grol all, the column. is to add spacing using addItem() with a QSpacerItem.
2) 感覺你tableWidget使用不規範,建議做成成員變數
self.tableWidget = None
然後contextGrid初始化,之後根據條數動態的往裡面加資料。